C++ has three main loop types: the for loop, the while loop and the do-while loop. Each one repeats a block of code while a condition holds. They differ in when the condition is checked and in what each one is best for.
The three loop types at a glance
| Loop | When the condition is checked | Minimum passes | Best for |
|---|---|---|---|
for |
Before each pass | 0 | A known number of passes, or walking through a range |
while |
Before each pass | 0 | Repeating until something changes, such as user input |
do-while |
After each pass | 1 | A body that must run at least once, such as a prompt |
The for loop
A for loop puts the starting value, the condition and the update step on one line:
#include <iostream>
int main() {
for (int i = 0; i < 3; ++i) {
std::cout << i << '\n';
}
return 0;
}
Output:
0
1
2
The int i = 0 part runs once at the start, i < 3 is checked before each pass, and ++i runs after each pass. Since C++11, a range-based form walks through each element of a container without a counter, such as for (int value : values) when values is a std::vector<int>.
The while loop
A while loop checks its condition before each pass, so the body can run zero times. It suits cases where the number of passes depends on something that changes inside the loop:
int i = 0;
while (i < 3) {
std::cout << i << '\n';
++i;
}
This prints the same three lines as the for loop above. For the full rules, including common mistakes, see c while loop syntax.
The do-while loop
A do-while loop checks its condition after each pass, so the body always runs at least once. The condition is followed by a semicolon:
#include <iostream>
int main() {
int count = 10;
do {
std::cout << count << '\n';
} while (count < 5);
return 0;
}
The condition is false from the start, but the body still runs once and prints 10. For more examples, see the do while loop in c example program.
Which loop to choose
- Use
forwhen you know the count or are walking through a range. - Use
whilewhen you need to repeat until a condition changes and cannot say in advance how many passes that will take. - Use
do-whilewhen the body must run at least once.
Recursion is another way to repeat work without a loop. A recursive function in c calls itself until a base case stops it, but for simple counting a loop is usually easier to follow.