C++ Loops: for, while, do-while, and Range-for
C++ has four loop forms, and each one fits a different job. A for loop fits a counted run. A while loop fits a run that ends on a condition. A do-while loop fits a run that must happen at least once. A range-for fits a walk over every value in a container, with no index to manage. This guide runs one main program. The program sums 1 to 5 and prints for sum=15, counts a while loop down from 3 to 1, walks a vector and prints range x=10, range x=20, and range x=30, and runs a do-while twice. Three smaller programs then show the traps: a do-while that runs once with a false condition, a range-for that changes nothing because it visits copies, and a one-character change from < to <= that runs a loop six times instead of five.
Written November 11, 2026 · 5 min read
- The main program: four loops in one file
- The for loop: a counted run
- The while loop: a condition checked first
- The do-while loop: a condition checked last
What this guide is
A loop runs the same block of code more than once. C++ gives a program four loop forms. The counted form is for. The condition-first forms are while and do-while. The container form is the range-based for, written range-for in this guide. This guide runs one main program that uses all four forms. Three smaller programs then isolate one rule each: when a do-while runs, what a range-for visits, and how the loop condition sets the count.
The main program: four loops in one file
#include <iostream>
#include <vector>
int main() {
int sum = 0;
for (int i = 1; i <= 5; ++i) sum += i;
std::cout << "for sum=" << sum << "\n";
int n = 3;
while (n > 0) { std::cout << "while n=" << n << "\n"; --n; }
std::vector<int> v = {10, 20, 30};
for (int x : v) std::cout << "range x=" << x << "\n";
int d = 0;
do { std::cout << "do d=" << d << "\n"; ++d; } while (d < 2);
for (int i = 0; i < 5; ++i) { if (i == 2) continue; if (i == 4) break; std::cout << "ctl i=" << i << "\n"; }
return 0;
}
The exact output:
for sum=15
while n=3
while n=2
while n=1
range x=10
range x=20
range x=30
do d=0
do d=1
ctl i=0
ctl i=1
ctl i=3
Each block of lines is one loop form doing its job. The for loop adds the numbers 1 to 5. The while loop prints a countdown. The range-for prints each value in the vector. The do-while loop prints two values. The last for loop prints three of its five values, because continue skips one and break stops the loop before the last one. The sections below take each form in turn.
The for loop: a counted run
A for loop packs three parts into one line. The first part runs once at the start. The second part is the condition, checked before each run of the body. The third part runs after each run of the body. In the main program the line reads for (int i = 1; i <= 5; ++i). The variable i starts at 1. The body adds i to sum while i is at most 5. The increment ++i raises i by one after each addition. The additions are 1, 2, 3, 4, and 5, so sum ends at 15 and the program prints for sum=15.
The counted form fits when the program knows the count in advance, or when it needs the counter value inside the body. The counter is declared inside the loop header, so it exists only for the loop. Code after the loop cannot read it by accident, and a second loop can reuse the name i with no conflict.
The while loop: a condition checked first
A while loop has only the condition. The program checks the condition before the first run of the body, and again before each later run. In the main program, n starts at 3 and the condition is n > 0. The body prints n and then lowers it with --n. The prints are 3, 2, and 1. When n reaches 0 the condition is false, and the loop stops without printing 0.
The condition-first form fits when the count is not known in advance. A program reads lines until the input ends, retries until a call succeeds, or walks a structure until it finds a null pointer. In each case the loop body itself must move the program toward the end condition. In the countdown, the --n statement does that work. A while body that never changes the values in its condition runs forever, which is the trap section's first warning.
The do-while loop: a condition checked last
A do-while loop moves the check to the end. The body runs once, then the condition decides whether it runs again. The main program runs do { std::cout << "do d=" << d << "\n"; ++d; } while (d < 2); with d starting at 0. The body prints 0, raises d to 1, and the condition d < 2 is true, so the body runs again. It prints 1, raises d to 2, and the condition is now false, so the loop stops. The output is do d=0 and do d=1.
The difference between the two condition forms shows when the condition starts out false. A second program sets d to 5 and runs both forms against the condition d < 2:
#include <iostream>
int main() {
int d = 5;
while (d < 2) { std::cout << "while d=" << d << "\n"; ++d; }
std::cout << "while done d=" << d << "\n";
do { std::cout << "do d=" << d << "\n"; ++d; } while (d < 2);
std::cout << "do done d=" << d << "\n";
return 0;
}
The exact output:
while done d=5
do d=5
do done d=6
The while loop prints nothing and leaves d at 5, because its condition is false at the first check. The do-while loop prints do d=5 once and leaves d at 6, because its body runs before the first check. That one guaranteed run is the whole reason the form exists. It fits code that must act before it can test: print a menu and then ask whether to continue, or try a read and then test whether any data arrived. One syntax trap belongs to this form alone: the closing line ends with a semicolon, } while (d < 2);. Leaving that semicolon out is a compile error.
The range-for loop: every value, no index
A range-for visits each value in a container in order. The main program runs for (int x : v) over the vector {10, 20, 30} and prints range x=10, range x=20, and range x=30. There is no index variable, no size check, and no condition to write. The loop cannot run past the end of the vector, because the loop itself takes its count from the container.
The counted for and the range-for answer different questions. The counted form fits when the body needs the position, when the walk goes backward, or when the step is larger than one. The range-for fits when the body needs only the values, in order, from start to end. Most container walks are the second kind, so the range-for is the default choice for reading a container. Writing through it takes one extra character, and that is the trap section's second warning.
break and continue: leaving early and skipping once
Two statements change a loop from inside its body. The statement continue ends the current run of the body and moves to the next value. The statement break ends the whole loop at once. The last loop in the main program shows both:
for (int i = 0; i < 5; ++i) { if (i == 2) continue; if (i == 4) break; std::cout << "ctl i=" << i << "\n"; }
The counter takes the values 0, 1, 2, 3, and 4 in turn, but the output is only ctl i=0, ctl i=1, and ctl i=3. At i equal to 2, continue skips the print and the loop moves to 3. At i equal to 4, break ends the loop, so 4 is never printed and no further values are tried. Both statements work in all four loop forms. In a while or do-while loop, continue jumps to the condition check, so any increment placed after the continue point in the body is skipped for that run. That is a common way to build an infinite loop by accident.
Trap: a range-for over copies changes nothing
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {10, 20, 30};
for (int x : v) x += 1;
std::cout << "after copy v=" << v[0] << " " << v[1] << " " << v[2] << "\n";
for (int& x : v) x += 1;
std::cout << "after ref v=" << v[0] << " " << v[1] << " " << v[2] << "\n";
return 0;
}
The exact output:
after copy v=10 20 30
after ref v=11 21 31
The first loop adds 1 to each copy and throws the copies away, so the vector still holds 10, 20, and 30. The second loop declares the variable as int&, a reference to the value in the vector, so each addition lands in the vector itself, which then holds 11, 21, and 31. The rule is short. To read values, for (int x : v) is fine, and for (const int& x : v) avoids a copy of each value, which matters for large element types. To change values in place, the reference form is required: for (int& x : v).
Trap: < and <= differ by one run
#include <iostream>
int main() {
int less = 0;
for (int i = 0; i < 5; ++i) ++less;
int lesseq = 0;
for (int i = 0; i <= 5; ++i) ++lesseq;
std::cout << "less count=" << less << " lesseq count=" << lesseq << "\n";
return 0;
}
The exact output:
less count=5 lesseq count=6
The loop with i < 5 runs for i equal to 0, 1, 2, 3, and 4: five runs. The loop with i <= 5 adds i equal to 5: six runs. Neither form is wrong on its own. Each is wrong when the count it gives is not the count the program needs, such as the number of elements in an array with indexes 0 to 4. The main program uses the other pairing on purpose: it starts at 1 and uses i <= 5, so its runs are 1, 2, 3, 4, and 5, which are the values it sums. Read a counted loop by naming its first value, its last value, and its count, in that order. If the three do not agree, the condition is the bug. The related failure is a loop that never ends: a while loop whose body forgets to change the condition's values, or a counted loop whose increment moves the counter away from the limit. Both run until the program is stopped from outside.
Which loop for which job
| Job | Loop | Why |
|---|---|---|
| A known count, or the counter is needed in the body | for |
Init, condition, and increment sit in one header, as the sum loop shows |
| An unknown count that ends on a condition | while |
The condition is checked first and the body moves toward it, as the countdown shows |
| Work that must run at least once before any test | do-while |
The body runs before the first check, as the d at 5 program shows |
| Every value in a container, in order, values only | range-for | No index and no condition, and the container sets the count |
| Every value in a container, changed in place | range-for with & |
The reference form writes into the container, as the 11, 21, 31 output shows |
The deciding question is what ends the loop. A count means for. A condition that may already be false means while. A first run that must happen means do-while. The end of a container means range-for.
Checklist
- Before writing a counted loop, name the first value, the last value, and the count. Check that the condition gives that count.
- Before writing a
whileloop, point at the statement in the body that moves the program toward the end condition. If there is none, the loop does not end. - Before choosing
do-while, confirm the body is safe to run once with the condition already false. That first run always happens. - Before ending a
do-whileloop, check the semicolon after the closing condition. This form needs it. - Before changing values in a range-for, declare the loop variable with
&. Without it, the loop changes copies. - Before placing
continuein awhilebody, check that the increment does not sit after it. A skipped increment can stall the loop.
Related guides on this site
- C++ Variables and Data Types — the foundation guide before this one, on declaring variables, the size of each type, and narrowing conversions.
- C++ Pointers and References — the guide that explains the reference the range-for trap uses, with addresses and dereferencing run on real code.
- C++ STL Containers: vector, map, and set by Example — the containers guide, on the vector this guide walks and the map and set that pair with it.
Sources
- cppreference, for loop — the counted loop: init statement, condition, and iteration expression, in that order.
- cppreference, while loop — the
whileform, which checks its condition before each run of the body. - cppreference, do-while loop — the
do-whileform, which checks its condition after each run, so the body always runs at least once. - cppreference, range-based for loop — the range-for form, its loop variable, and the reference form that writes into the container.
Keep Exploring
Seven tips and seven puzzles so far, each one a short runnable example with the fix explained.
Paste an AddressSanitizer, UBSan, or ThreadSanitizer report and get the bug, the file and line, and the fix \u2014 in plain language.
C++20 and C++23 features, migration paths, and measured trade-offs.
The full C++ hub \u2014 language basics, the standard library, coroutines, and measured comparisons.
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.