The Analogy: Filling a Bath
A for loop is "do this exactly twenty times". A while loop is "keep running the tap until the bath is full" — you do not know in advance how many seconds that will take, only the condition that makes you stop.
That is the entire distinction. Use while when the number of repetitions depends on something discovered while running: input from a user, lines in a file, a value converging, a search finding its target. Use for when you can state the count up front.
And the bath analogy carries the danger too: if nothing ever fills the bath, the tap runs forever.
Syntax or Core Structure
#include <iostream>
int main() {
// The three parts of every while loop
int count{1}; // 1. set up state BEFORE the loop
while (count <= 5) { // 2. test the condition
std::cout << count << " ";
++count; // 3. change the state, or loop forever
}
std::cout << "\n"; // 1 2 3 4 5
// Condition false on entry -- body never runs at all
int n{100};
while (n < 10) {
std::cout << "never printed\n";
}
// Driven by input rather than a counter
int value{};
int total{};
std::cout << "Numbers (0 to stop): ";
while (std::cin >> value && value != 0) {
total += value;
}
std::cout << "Total: " << total << "\n";
// Deliberate infinite loop with an internal exit
while (true) {
std::cout << "tick\n";
break; // something must break out
}
return 0;
}
The condition is checked before each pass, including the first. If it is false immediately, the body executes zero times — which is often exactly what you want.
Technical Depth: Infinite Loops, Invariants and Streams
The four ways a loop never ends
// 1. You forgot to change the state
int i{0};
while (i < 5) { std::cout << i; } // i is never incremented
// 2. You changed the wrong variable
int a{0}, b{0};
while (a < 5) { ++b; } // a never moves
// 3. The condition can never become false
unsigned int u{5};
while (u >= 0) { --u; } // unsigned is NEVER negative:
// 0 - 1 wraps to 4294967295
// 4. Floating point never lands exactly on the target
double d{0.0};
while (d != 1.0) { d += 0.1; } // 0.1 is inexact -- d skips past 1.0
// fix: while (d < 1.0)
Case three is the one that catches experienced programmers, because the code looks obviously correct. Any countdown to zero must use a signed type, or restructure to while (u > 0) and decrement inside.
Think in terms of the loop invariant
Before writing a while, answer three questions:
- What must be true before the first pass? (initialisation)
- What stays true on every pass? (the invariant)
- What makes progress toward stopping? (the decreasing measure)
// Sum of digits: invariant is "total holds the digits removed so far"
int number{4821};
int total{0};
while (number > 0) {
total += number % 10; // take the last digit
number /= 10; // remove it -- this is the progress
}
std::cout << total << "\n"; // 15
number /= 10 is the decreasing measure: it strictly shrinks every pass and cannot shrink below zero, so the loop must end. If you cannot name that measure, you probably have an infinite loop.
Reading until input runs out
#include <string>
std::string line;
while (std::getline(std::cin, line)) { // false at end of input
std::cout << line.size() << ": " << line << "\n";
}
int value{};
while (std::cin >> value) { // false at EOF or on bad input
std::cout << value * 2 << "\n";
}
This is the idiomatic C++ read loop. The stream converts to bool, so the condition means "the read succeeded". Do not write while (!std::cin.eof()) — the EOF flag is only set after a read fails, so that version processes the last item twice.
Nested while loops
int row{1};
while (row <= 3) {
int col{1}; // reset the inner counter each time!
while (col <= 3) {
std::cout << row * col << "\t";
++col;
}
std::cout << "\n";
++row;
}
Declaring col inside the outer body means it is created fresh every pass. Declare it outside and the inner loop runs once and never again — its counter is already past the limit.
While versus for
while | for | |
|---|---|---|
| Best for | unknown number of passes | a known count or range |
| Counter scope | outside the loop, still alive after | inside the loop header |
| Typical driver | input, a flag, convergence | an index, a container |
| Risk | forgetting to update state | off-by-one in the bounds |
Anything one can do, the other can too — for (;condition;) is a while. Choose the one that makes your intent obvious.
Real World Example: A Number-Guessing Game
#include <iostream>
#include <limits>
#include <random>
int main() {
// Modern C++ random: a seeded engine and a distribution
std::random_device seed;
std::mt19937 engine{seed()};
std::uniform_int_distribution<int> range{1, 100};
const int secret = range(engine);
const int maxAttempts{7};
int attempts{0};
bool won{false};
std::cout << "Guess a number from 1 to 100. You have "
<< maxAttempts << " tries.\n";
// Two exit conditions: they won, or they ran out
while (!won && attempts < maxAttempts) {
std::cout << "Guess " << (attempts + 1) << ": ";
int guess{};
if (!(std::cin >> guess)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Numbers only.\n";
continue; // does NOT count as an attempt
}
++attempts; // only a real guess counts
if (guess == secret) {
won = true;
} else if (guess < secret) {
std::cout << "Too low.";
} else {
std::cout << "Too high.";
}
if (!won) {
std::cout << " " << (maxAttempts - attempts) << " left.\n";
}
}
if (won) {
std::cout << "Correct in " << attempts << " attempts.\n";
} else {
std::cout << "Out of tries. It was " << secret << ".\n";
}
return 0;
}
The loop condition combines both ways the game can end, so there is exactly one exit point and the code after the loop can simply ask which happened. continue on bad input skips the increment, so typing letters does not burn a guess — a small decision that comes straight from the loop's structure. And because won is set rather than break being called, the summary logic after the loop stays simple.
Common Mistakes
- Forgetting to update the loop variable. The condition never changes and the program hangs.
- Counting down with an unsigned type.
while (u >= 0)never ends because unsigned values wrap. while (!std::cin.eof()). Processes the final item twice. Usewhile (std::cin >> x).- A semicolon after the condition:
while (i < 5);gives an empty body and hangs immediately. - Declaring the inner counter outside the outer loop, so the nested loop runs only once.
- Comparing doubles with
!=as the stopping test. Use<or a tolerance. - Using
continuein awhilebefore the increment, which skips it and hangs — the one placecontinueis genuinely more dangerous inwhilethan infor.
Best Practices
- Name the progress measure before you write the loop. If nothing strictly decreases or advances, the loop will not end.
- Initialise the loop variable immediately before the loop, not fifty lines earlier.
- Use
while (stream >> value)for reading; never testeof()yourself. - Prefer one exit condition in the
whileheader over scatteredbreakstatements. - Put
continueafter any increment, or useforwhere the increment cannot be skipped. - Add a safety counter to loops driven by external state:
while (!ready && ++tries < 1000)fails loudly instead of hanging.
Practice Exercises
- Digit reverser: Read an integer and print it backwards using only
%and/in awhileloop —4821becomes1284. - Collatz length: For a starting number, repeatedly halve it if even or triple-plus-one if odd, counting steps until it reaches 1. Print the count for every start from 1 to 20 and report which took longest.
- Menu loop: Build a
while (running)menu with options to add a number to a running total, show the total, reset it, and quit. Handle invalid input without ending the program or hanging.