Explain it simply
Explain it simply
A loop runs the same block of code again and again, so you write it once instead of copying it ten or ten thousand times. Printing every item in a list, adding up a column of numbers, retrying a download and redrawing a game screen sixty times a second are all loops.
Every loop answers one question before each round: should I go again? A for loop is best when you count, as in "do this 10 times". A while loop is best when you wait for something to change, as in "keep reading until the file ends". A range-based for walks through every element of a collection without any counter at all.
Problem → Why → Solution
The problem: one item too many
A shop prints its three daily prices with a counting loop. The loop is written with <= because "from 0 up to 3" sounds right. The list prints the three real prices and then a fourth, nonsense number, or the program crashes, depending on the day. Nothing in the source looks obviously wrong, which is why off-by-one errors are among the most common bugs in any language.
#include <iostream>
#include <vector>
int main() {
std::vector<int> prices = {1500, 2500, 4000};
for (std::size_t i = 0; i <= prices.size(); ++i) { // <= runs 4 times
std::cout << prices[i] << '\n'; // prices[3] does not exist
}
return 0;
}Where does the fourth round come from?
A collection of three elements has the valid indexes 0, 1 and 2. The condition i <= prices.size() is still true when i reaches 3, so the body runs a fourth time and reads prices[3], one past the end. The [] operator does not check bounds, so that read is undefined behaviour rather than an error. Counting loops over a size should almost always use <, and a range-based for avoids the index entirely.
Core concept: one test before every round
A for loop has three parts inside its parentheses, separated by semicolons: for (init; condition; update). The init runs once, before anything else, and usually declares a counter such as int i = 1. Then the condition is tested; if it is false, the loop ends immediately, possibly without running the body at all. If it is true, the body runs, then the update (often ++i) runs, and the condition is tested again. A counter declared in the init exists only inside the loop.
A while (condition) loop has only the condition. Whatever the body does must eventually make that condition false, otherwise the loop never ends. A do { ... } while (condition); loop moves the test to the bottom, so its body always runs at least once, which suits "ask, then check the answer" situations such as menus.
The range-based for loop, for (element : collection), visits every element of a container such as a std::vector or a std::string, in order. There is no counter to get wrong. The declaration decides what you get: auto copies each element, const auto& reads it without copying, and auto& lets you modify the element inside the container.
Two keywords change the flow inside any loop. break leaves the innermost loop at once, and continue skips the rest of the current round and jumps to the next test (or, in a for loop, to the update). Use them for early exits, such as stopping at the first match, rather than for normal control flow.
| Loop | Tests the condition | Typical use |
|---|---|---|
| for | before each round | counting a known number of times |
| while | before each round | waiting until something changes |
| do-while | after each round | run once, then repeat while needed |
| range-based for | no condition | every element of a collection |
- Run init once
- Test the condition: false ends the loop
- Run the body
- Run the update, then test again
A loop whose condition is false at the start runs its body zero times; only do-while is guaranteed one round.
General pattern
for (int i = start; i < end; ++i) { /* counted work */ }
while (condition) { /* must eventually make condition false */ }
do { /* runs at least once */ } while (condition);
for (const auto& element : collection) { /* each element, no copy */ }
// inside any loop: break leaves it, continue skips to the next roundUse for when you know the count, while when you wait for a condition to change, do-while when the body must run at least once, and range-based for to visit a whole collection.
Example: counting, a countdown and a total
This program has three loops: a for loop that counts from 1 to 3, a while loop that counts down from 3, and a range-based for loop that adds up a list of scores. Count how many times each body runs before you check the output.
#include <iostream>
#include <vector>
int main() {
for (int i = 1; i <= 3; ++i) {
std::cout << "For loop count: " << i << '\n';
}
int countdown = 3;
while (countdown > 0) {
std::cout << "Countdown: " << countdown << '\n';
--countdown;
}
std::vector<int> scores = {72, 85, 90};
int total = 0;
for (int score : scores) {
total += score;
}
std::cout << "Total score: " << total << '\n';
return 0;
}Code breakdown
- Counting for loop
for (int i = 1; i <= 3; ++i) {i starts at 1, and the body runs while i <= 3 is true: for 1, 2 and 3. Here <= is correct because we count from 1 to 3 inclusive; it is with 0-based indexes that < is the right choice.
- While condition
while (countdown > 0) {Tested before every round. It is true for 3, 2 and 1 and false once countdown reaches 0, so the body runs three times.
- Progress step
--countdown;This line is what makes the while loop finish. Delete it and countdown stays 3 forever: the program prints Countdown: 3 until you stop it.
- A collection
std::vector<int> scores = {72, 85, 90};std::vector is the standard growable list (the STL vector lesson covers it in depth). Here it simply holds three ints for the next loop to visit.
- Range-based for
for (int score : scores) {Visits 72, 85 and 90 in order, copying each into score. Copying an int costs nothing; for larger elements such as strings, const auto& avoids the copy.
- Accumulator
total += score;total must start at 0 before the loop. Each round adds one score, giving 72 + 85 + 90 = 247.
For loop count: 1
For loop count: 2
For loop count: 3
Countdown: 3
Countdown: 2
Countdown: 1
Total score: 247- init: i = 1
- i <= 3 ?
- body
- ++i
condition true
run body, then update
condition false
exit loop
break and continue
The snippet scans a list of temperature readings. A reading of -999 is a sensor error, so continue skips it without stopping the scan. The first reading above 40 is an emergency, so break ends the loop at once, and the remaining readings are never examined.
#include <iostream>
#include <vector>
int main() {
std::vector<int> readings = {31, -999, 35, 42, 38};
int checked = 0;
for (int t : readings) {
if (t == -999) {
continue; // skip a broken reading
}
++checked;
if (t > 40) {
std::cout << "Too hot: " << t << '\n';
break; // stop at the first emergency
}
}
std::cout << "Readings checked: " << checked << '\n';
return 0;
}The output is Too hot: 42 and Readings checked: 3: 31, 35 and 42 are counted, -999 is skipped, and 38 is never reached.
Copy, read or modify: the range-for declaration
The variable in a range-based for is a fresh declaration on every round, so the ordinary rules apply. A plain auto (or std::string) is a copy, and changes to it vanish at the end of the round. const auto& is a read-only alias, cheap even for long strings. auto& is a writable alias, so changes land in the container itself.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> names = {"Aye", "Bo", "Chit"};
for (auto name : names) {
name += "!"; // changes a copy only
}
for (auto& name : names) {
name += "?"; // changes the element in the vector
}
for (const auto& name : names) {
std::cout << name << ' '; // read-only, no copies
}
std::cout << '\n';
return 0;
}The output is Aye? Bo? Chit?: the ! added to the copies is gone, and only the ? added through the reference remains.
In real projects
Where this shows up in real projects
Loops are the engine of nearly every program. A web server's main loop waits for a connection, handles it and goes back to waiting for as long as it runs. A game loop reads input, updates the world and draws a frame, usually sixty or more times per second. Batch jobs loop over every row of a file or database table, and retry logic loops with a limit, as in "try the download up to three times".
In modern C++ code, a range-based for with const auto& is the default way to walk a container, because it cannot go out of bounds and never copies by accident. Index loops remain for when you need the position itself, such as printing "1. Aye" or comparing neighbours. Many teams go one step further and replace hand-written loops with standard algorithms such as std::accumulate or std::ranges::count_if, which the algorithms lesson later in this course introduces.
Common mistakes
Common mistakes
1. Using <= with a 0-based size
for (std::size_t i = 0; i <= v.size(); ++i) runs one extra round and reads v[v.size()], past the end. With 0-based indexes the condition is i < v.size(); better still, use a range-based for.
2. Counting down with an unsigned counter
for (std::size_t i = word.size() - 1; i >= 0; --i) never ends: an unsigned value is always >= 0, and decrementing 0 wraps to a huge number. g++ -Wextra says comparison of unsigned expression in '>= 0' is always true [-Wtype-limits]. Count down with for (std::size_t i = word.size(); i-- > 0;) or use a signed counter.
3. Mixing int counters with size()
for (int i = 0; i < word.size(); ++i) compares a signed int with an unsigned size, and g++ -Wall warns comparison of integer expressions of different signedness. Declare the counter as std::size_t, or use a range-based for, so the types match.
4. Forgetting the update in a while loop
If nothing in the body moves the condition toward false, as with a missing --countdown, the loop spins forever and the program appears to hang. Before running a while loop, make sure you can point to the line that makes it finish.
Best practices
Best practices
- Prefer a range-based for with const auto& whenever you do not need the index.
- Use < with 0-based indexes, and declare the counter in the for header so it cannot leak.
- Give every while loop an obvious exit, and add a maximum count to retry loops.
- Keep loop bodies short and move long ones into functions.
Mini challenge
Mini challenge: three loops, three jobs
Pick the best loop for each job: for to count, while to wait for a change, and range-based for to inspect a collection.
- Print 7 x 1 = 7 up to 7 x 5 = 35 with a for loop
- With a while loop, halve amount (1000) by integer division until it reaches 1, counting the steps
- With a range-based for, find the hottest day and count the days above 30
- Choose correctly between < and <= in any counting loop
#include <iostream>
#include <vector>
int main() {
std::vector<int> temperatures = {29, 31, 36, 28, 30};
int amount = 1000;
// TODO: for loop: print "7 x 1 = 7" up to "7 x 5 = 35"
// TODO: while loop: halve amount until it is 1 and count the steps
// TODO: range-based for: track the hottest value and count days above 30
return 0;
}Expected: The output should be: 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 Halvings: 9 Hottest: 36 Days above 30: 2
Show hint
The halving loop's condition is amount > 1, and its body does amount /= 2; plus ++ on a counter. To find the hottest day, start hottest at the first element (temperatures[0]) and replace it whenever you see a bigger value.
Show solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> temperatures = {29, 31, 36, 28, 30};
int amount = 1000;
for (int i = 1; i <= 5; ++i) {
std::cout << "7 x " << i << " = " << 7 * i << '\n';
}
int halvings = 0;
while (amount > 1) {
amount /= 2;
++halvings;
}
std::cout << "Halvings: " << halvings << '\n';
int hottest = temperatures[0];
int hotDays = 0;
for (int t : temperatures) {
if (t > hottest) {
hottest = t;
}
if (t > 30) {
++hotDays;
}
}
std::cout << "Hottest: " << hottest << '\n';
std::cout << "Days above 30: " << hotDays << '\n';
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- for (init; condition; update) runs init once, then tests, runs the body and updates until the condition is false.
- while tests before each round and needs a body that eventually makes its condition false; do-while always runs once.
- A range-based for visits every element: auto copies, const auto& reads, auto& modifies.
- Use < with 0-based indexes, and watch out for unsigned counters when counting down.
- break leaves the innermost loop, and continue skips to the next round.
The Current ISO C++ Standard (C++23) — Standard C++ Foundation