“Know how to solve every problem that has been solved.” “What I cannot create, I do not understand.” — Richard Feynman

While Loop

Programming

Audited·on 2026-05-14·short read

This program demonstrates the while loop, which executes a block of code repeatedly as long as a condition is true.

Implementation

#include <iostream>

int main() {
    int i = 1;
    int max_count = 5;

    std::cout << "Max Count: " << max_count << std::endl;
    while (i <= 5) {
        std::cout << "Count: " << i << std::endl;
        ++i;
    }
    return 0;
}

Key Concepts

Output

Max Count: 5
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

When to use while vs. for

Both while and for compile to identical machine code. The choice between them is stylistic — about which form most clearly expresses what the loop is doing. The convention:

Concrete example. Walking a null-terminated C string until you hit the end is the canonical while pattern:

int len = 0;
while (s[len]) ++len;

Rewriting as a for works but leaves two of the three slots empty, which reads awkwardly:

int len = 0;
for (; s[len]; ++len);

Identical machine code, identical behavior — just a stylistic mismatch. The for loop's syntax was designed for counted loops where all three slots carry weight; walking a string is not that. When you see a C/C++ codebase walking a null-terminated string, it's almost always while.