for, while and do-while
What you'll learn:
- repeat an action with
for,whileanddo-whileloops; - count how many times a loop runs without an off-by-one error;
- walk through a list of values with a range-for loop;
- leave a loop early with
breakand skip an iteration withcontinue.

To print the numbers 1 to 5, you can write five lines with std::cout. A thousand numbers would take a thousand lines. Instead, you write a loop, a construct that repeats an action while a condition holds.
Picture a runner at a stadium. The coach says, "Keep running laps until you've done five."
The runner steps up to the start line. Before each lap they pass under a checkpoint arch, which checks how many laps are done. Then the runner runs the lap and puts a mark in a notebook. A loop works the same way:
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
std::cout << i << ' '; // 1 2 3 4 5
}
std::cout << '\n';
}How a for loop runs
The for header has three parts separated by semicolons. Each one matches a part of the stadium, and they run in this order:
- The initialization
int i = 1runs once, before the loop starts. This is the start line. - The condition
i <= 5is checked before every pass. This is the checkpoint arch: if the condition is true, the body runs; if it is false, the loop ends. - The body in curly braces runs. This is the lap itself.
- The step
++iruns after the body. This is the mark in the notebook. Then the loop goes back to item 2.
The widget runs the same loop with the condition i <= 3: press "Next step" and watch when each part of the header runs.
1–2#include <iostream>3int main() {4 for (int i = 1; i <= 3; ++i) {5 std::cout << i << "\n";6 }7 std::cout << "end\n";8}
The initialization int i = 1 runs once
One pass through the body is called an iteration. This is where the analogy stops: a real runner knows how far they have run, while the loop remembers only the value of i.
When i becomes 6, the condition is false and the loop ends. The variable i is declared in the header, so it is visible only inside the loop. After the closing curly brace of the loop body, the name i no longer exists.
Counting iterations
A loop runs as many times as there are values its counter i takes. In for (int i = 0; i < 5; ++i), those are the values 0 to 4, that is, five iterations. The < sign keeps i from reaching the bound itself.
Replace < with <=, and i reaches 5 too, which makes six iterations. A loop that runs one time too many or too few has an off-by-one error. Interviewers like to show such loops and ask how many times the body runs.
while and do-while loops
A for loop keeps all three parts in its header. The two other kinds of loop are simpler.
The while loop
A while loop checks its condition before every iteration, like for, but it has no initialization or step. The variable is declared before the loop and changed in the body. You pick it when the number of iterations is not known in advance. This is how you count how many integer divisions by 2 it takes to bring 100 down to 1:
int n = 100;
int steps = 0;
while (n > 1) {
n = n / 2;
++steps;
}
std::cout << steps << '\n'; // 6The values of n go 100, 50, 25, 12, 6, 3, 1. That is six divisions, and at 1 the condition n > 1 turns false.
The do-while loop
A do-while loop runs its body first and only then checks the condition. So its body runs at least once, even if the condition is false from the start. Compare two loops with the same false condition:
int n = 10;
while (n < 5) {
std::cout << n << '\n';
++n;
}
do {
std::cout << n << '\n'; // 10
++n;
} while (n < 5);Let's walk through what happens:
whilechecks10 < 5right away. The condition is false, the body never runs, and nothing is printed.doruns the body: it prints10and makesnequal to11.- Only now is
n < 5checked. The condition is false, and the loop ends.
A do-while loop ends with a semicolon after while (n < 5). Without it, the program does not compile.
Common mistake
An unsigned counter in a countdown loop:
for (unsigned i = 3; i >= 0; --i) { // ✗
std::cout << i << '\n';
}An unsigned value is never negative, so the condition i >= 0 is always true. Subtract one from 0, and you get the largest unsigned value, so the loop prints numbers forever. GCC with the -Wextra flag warns that the comparison is always true, but Clang stays silent even with -Wextra. To count down to zero, declare the counter as int: after 0 it becomes -1, and the condition turns false.
Key points
- The parts of a
forheader run in order: the initialization once, then the condition, the body, the step and the condition again. - A loop with
i = 0and the conditioni < nrunsntimes; with<=, it runs once more. whilechecks the condition before the body, anddo-whileafter it, so its body runs at least once.- An
unsignedcounter never drops below zero, so the conditioni >= 0is always true for it.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.