While Loop
Programming
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
while: Loop that continues while the condition is true++i: Pre-increment operator (increments before use)- The loop variable must be initialized before the loop and updated inside the loop
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:
-
whilewhen there's no init clause and no body — just a condition (with maybe an increment). -
forwhen all three slots make sense to fill:for (init; condition; increment), likefor (int i = 0; i < N; ++i).
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.