Loops repeat a block of code, which is one of the main reasons computers are useful. Instead of writing cout a hundred times, you write it once inside a loop that runs a hundred times.
C++ has three classic loops. The for loop is best when you know how many times to repeat. The while loop keeps going as long as a condition is true. The do-while loop is like while, but always runs at least once. Modern C++ also has a range-based for loop for walking through every item in a collection, which you'll use with vectors in a later lesson.
In this lesson you'll use each loop, nest one loop inside another, and control loops with break and continue.
The for loop
for (int i = 0; i < 5; i++) {
cout << i << " ";
}The three parts in the brackets are:
- Initialisation:
int i = 0runs once, before the loop starts. - Condition:
i < 5is checked before each pass. The loop stops when it's false. - Update:
i++runs after each pass.
This prints 0 1 2 3 4. i++ adds one; i-- subtracts one, and i += 2 counts in twos.
while and do-while
int coins = 3;
while (coins > 0) {
cout << "Spending a coin" << endl;
coins--;
}while checks the condition first, so if it's false from the start, the body never runs. do-while checks after the body, so the body always runs once:
int choice;
do {
cout << "1) Play 0) Quit: ";
cin >> choice;
} while (choice != 0);That makes do-while a natural fit for menus.
Nested loops
A loop can sit inside another loop. The inner loop runs completely for each pass of the outer one:
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
cout << "*";
}
cout << endl;
}This draws 3 rows of 4 stars. Nested loops are used for grids, tables and game boards.
break and continue
breakexits the nearest loop immediately.continueskips the rest of the current pass and moves to the next.
In a nested loop, break only leaves the inner loop. If you need to stop both, set a bool flag and check it in the outer loop, or move the loops into a function and use return.
Choosing a loop and counting backwards
| Situation | Loop to use |
|---|---|
| A known number of passes, or an index you need | for (int i = 0; i < n; i++) |
| Every item in a vector or string | for (auto x : items) |
| Repeat until something happens | while (condition) |
| The body must run at least once, like a menu | do { } while (condition); |
A for header can also manage more than one variable, separated by commas. This one walks inwards from both ends at once:
for (int left = 0, right = 10; left < right; left += 3, right -= 3) {
cout << left << "," << right << " "; // 0,10 3,7
}Counting backwards needs care with sizes. v.size() returns size_t, which is unsigned and can never be negative, so this loop never ends properly:
for (size_t i = v.size() - 1; i >= 0; i--) // i >= 0 is always trueWhen i is 0 and you subtract one, it wraps round to an enormous number. Use an int index, as in for (int i = static_cast<int>(v.size()) - 1; i >= 0; i--), or the pattern for (size_t i = v.size(); i-- > 0; ), which checks before it subtracts. Compiling with -Wall -Wextra warns about the always-true comparison.
C++ Loops Syntax
Loop syntax
for (int i = 0; i < n; i++) { }
while (condition) { }
do { } while (condition);
for (auto item : collection) { }C++ Loops Summary
for (init; condition; update)repeats a known number of times.while (condition)repeats while true;do { } while (condition);always runs once.- Inner loops run fully for each pass of an outer loop.
breakexits the nearest loop;continueskips to the next pass.- Make sure every while loop can eventually stop.
C++ Loops Examples
Each example shows the code, the output it produces and what each part does.
Sum of the numbers 1 to 100
#include <iostream>
using namespace std;
int main() {
int total = 0;
for (int i = 1; i <= 100; i++) {
total += i;
}
cout << "Sum: " << total << endl;
return 0;
}Sum: 5050Line-by-line explanation
- Line 5The running total starts at 0, before the loop.
- Lines 6 to 8Each pass adds the current number.
- Line 9After the loop, total holds 1 + 2 + ... + 100.
Halving with while
#include <iostream>
using namespace std;
int main() {
int n = 100;
int steps = 0;
while (n > 1) {
n = n / 2;
steps++;
cout << n << " ";
}
cout << endl << "Steps: " << steps << endl;
return 0;
}50 25 12 6 3 1
Steps: 6Line-by-line explanation
- Line 8Keep going while n is above 1.
- Line 9Integer division: 25 / 2 is 12, not 12.5.
- Line 10Count how many times the loop ran.
A multiplication grid
#include <iostream>
using namespace std;
int main() {
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= 4; col++) {
if (col == 3) continue;
cout << row * col << "\t";
}
cout << endl;
}
return 0;
}1 2 4
2 4 8
3 6 12
4 8 16 Line-by-line explanation
- Lines 5 to 6For each of 4 rows, the inner loop runs 4 times.
- Line 7continue skips column 3 in every row.
- Line 8"\t" is a tab, which lines the numbers up in columns.
Common C++ Loops Mistakes
Semicolon after the loop header
for (int i = 0; i < 3; i++); {
cout << "Hi" << endl;
}for (int i = 0; i < 3; i++) {
cout << "Hi" << endl;
}The semicolon is an empty loop body, so "Hi" prints just once.
A while loop that never ends
int i = 0;
while (i < 5) {
cout << i;
}int i = 0;
while (i < 5) {
cout << i;
i++;
}Off by one
for (int i = 1; i < 10; i++) { } // runs 9 timesfor (int i = 0; i < 10; i++) { } // runs 10 timesStarting at 0 and using < with the count is the usual pattern.
C++ Loops in Real Projects
Loops in C++ programs
A game's main loop runs about 60 times a second: read input, update the world, draw the frame. Image editors loop over every pixel in a picture using nested loops for rows and columns, which is exactly the shape of the multiplication grid above.
C++ Loops FAQ
How do I get the index in a range-based for loop?
The range-based loop doesn't provide one. Use a classic for loop when you need positions, or in C++20 declare a counter in the loop header: for (int i = 0; auto& x : items) { ...; i++; }. The counter is only visible inside the loop, just like a normal for variable.
How do I write an infinite loop on purpose?
Use while (true) { ... } or for (;;) { ... } and leave it with break or return when the job is done. This is common for game loops, servers and menus where the exit condition is checked in the middle of the body rather than at the top.
How do I loop through each character of a string?
Use a range-based loop: for (char c : word) { ... }. Write for (char& c : word) if you want to change the characters, for example to make them upper case. A classic loop with word[i] and i < word.size() works too when you need the position.
Is ++i faster than i++ in a for loop?
For an int loop counter, no: the compiler produces the same code for both. i++ has to keep a copy of the old value, which can cost something for more complex types such as iterators, so some programmers write ++i out of habit. Either is fine in beginner code; pick one and be consistent.
How do I keep reading numbers until the input ends?
Put the read in the condition: while (cin >> n) { total += n; }. The loop stops when the input runs out or the user types something that isn't a number. At the keyboard, you signal the end with Ctrl+D on Linux and macOS or Ctrl+Z then Enter on Windows.
C++ Loops Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the loop so it prints 1 to 5.
(int i = 1; i <= 5; i) {
cout << i << " ";
}
What does this print?
for (int i = 10; i > 0; i -= 3) {
cout << i << " ";
}
How many stars does this print?
for (int a = 0; a < 3; a++)
for (int b = 0; b < 4; b++)
cout << "*";
Which loop is best for a menu that must appear at least once?
What does this print?
for (int i = 0; i < 10; i++) {
if (i == 4) break;
if (i % 2 == 1) continue;
cout << i << " ";
}
C++ Loops Quiz
5 questions to check what you learned.
What does
i++do?- Doubles i
- Adds 1 to i
- Prints i
- Sets i to 0
In nested loops, what does
breakexit?- Only the innermost loop it's in
- Every loop
- The whole program
- Only the outer loop
When is a while loop's condition checked?
- After each pass
- Only once
- Before each pass
- Only when it changes
What is the value of
nafterint n = 0; while (n < 20) n += 7;?- 14
- 20
- 28
- 21
Which loop always runs its body at least once?
- do-while
- for
- while
- range-based for