C++ course menu
C++ Loops: for, while and do-while Explained
An introduction to loops in C++: the for loop, the while loop, the do-while loop, the range-based for loop, how to choose between them, and how to avoid infinite loops and off-by-one errors.
On this page
A loop repeats a block of code. Instead of writing the same line ten times, you write it once and let the loop run it as many times as needed. C++ has four kinds of loop; this lesson introduces all of them, and the next lessons go deeper.
The for loop#
Use for when you know how many times to repeat, or you are counting:
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
std::cout << "Lap " << i << '\n';
}
}Lap 1
Lap 2
Lap 3
Lap 4
Lap 5The parentheses hold three parts, separated by semicolons:
- Initialization
int i = 1: runs once, before the loop starts. - Condition
i <= 5: checked before every repetition; the loop stops when it is false. - Update
++i: runs after every repetition.
The while loop#
Use while when you do not know in advance how many repetitions you need, only the condition for continuing:
#include <iostream>
int main() {
int balance = 1000;
int years = 0;
while (balance < 2000) {
balance = balance * 110 / 100; // 10% growth per year
++years;
}
std::cout << "Doubled after " << years << " years: " << balance << '\n';
}Doubled after 8 years: 2142The condition is checked before each repetition, so if it is false at the start, the body never runs.
The do-while loop#
do ... while checks the condition after the body, so the body always runs at least once. That suits "ask until the answer is valid":
#include <iostream>
int main() {
int number = 0;
do {
std::cout << "Enter a number from 1 to 10: ";
std::cin >> number;
} while (number < 1 || number > 10);
std::cout << "Thanks, you chose " << number << '\n';
}Enter a number from 1 to 10: 15
Enter a number from 1 to 10: 7
Thanks, you chose 7Note the semicolon after while (...) in a do ... while. It is required here, unlike in a normal while.
The range-based for loop#
To visit every element of a collection, the range-based for loop is the simplest and safest choice:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> fruits = {"apple", "banana", "cherry"};
for (const std::string& fruit : fruits) {
std::cout << fruit << '\n';
}
}apple
banana
cherryRead it as "for each fruit in fruits". The const ... & avoids copying each string; you will learn why in References. It also works with arrays and strings (one char at a time).
Which loop should I use?#
Any loop can be rewritten as another kind; choose the one that makes the intent clearest.
Infinite loops#
If the condition never becomes false, the loop runs forever:
int i = 0;
while (i < 5) {
std::cout << i << '\n';
// forgot ++i, so i stays 0 forever
}If your program hangs, press Ctrl + C in the terminal to stop it, then check that something inside the loop moves it towards its end. Sometimes an endless loop is intended, such as a game loop or server; it is written while (true) and left with break (see break and continue).
Off-by-one errors#
The most common loop bug is running one time too many or too few. Compare:
#include <iostream>
int main() {
for (int i = 0; i < 3; ++i) std::cout << i << ' ';
std::cout << '\n';
for (int i = 0; i <= 3; ++i) std::cout << i << ' ';
std::cout << '\n';
}0 1 2
0 1 2 3i < 3 runs 3 times (0, 1, 2); i <= 3 runs 4 times. When looping over the positions of an array with n elements, use i = 0; i < n.
Common mistakes#
Practice#
Practice exercise
Print the multiplication table of 7 from 7 x 1 = 7 to 7 x 10 = 70.
Show solution
#include <iostream>
int main() {
for (int i = 1; i <= 10; ++i) {
std::cout << "7 x " << i << " = " << 7 * i << '\n';
}
}7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70Practice exercise
Using a while loop, find how many times you must halve 1000 (with integer division) before it becomes less than 1. Print the count.
Show solution
#include <iostream>
int main() {
int n = 1000;
int steps = 0;
while (n >= 1) {
n /= 2;
++steps;
}
std::cout << steps << '\n';
}10The values go 500, 250, 125, 62, 31, 15, 7, 3, 1, 0, which is 10 halvings.
Key takeaway#
Finished this lesson?