C++ Loops and Repetition
Choose for, while, and range-based loops from the stopping rule, then avoid off-by-one errors, accidental infinite loops, and invalid ranges.
Before this lesson
Select a loop from its stopping rule
Trace counters accumulators and sentinels
Prevent off-by-one and non-progressing loops
The short answer
A loop repeats while a condition remains true. Use a range-based for loop for every element, a counted for loop for a known progression, and while when the stopping condition is driven by state or input.
Every loop needs progress and a stop
Before writing syntax, state what repeats, what changes, and what ends the repetition. A loop that does not move toward its stopping condition can run forever. A loop that stops one step late can access invalid memory or count an extra item.
Trace a small input by hand. Record the condition, current value, body effect, and update for each iteration. This exposes whether the boundary is inclusive and whether the final state matches the requirement.
| Situation | Loop shape | Reason |
|---|---|---|
| Count 1 through 10 | for | Known progression |
| Read until sentinel | while | Stop depends on input |
| Visit every value | range-based for | No index required |
| Menu until quit | while | State controls continuation |
For expresses a progression
A traditional for loop places initialization, continuation, and update together. Use it when the progression is central, such as visiting positions or generating a known range. Keep the body focused on the work for one iteration.
#include <iostream>
int main()
{
int sum{};
for (int number{1}; number <= 5; ++number)
{
sum += number;
}
std::cout << "Sum: " << sum << '\n';
}Expected output
Sum: 15
While follows changing state
while checks before each iteration, so the body may run zero times. This matches input loops and state machines. Initialize the state before the loop, update it on every path that continues, and keep the sentinel out of ordinary data processing.
Failed input is another stopping state. while (std::cin >> value) reads values until extraction fails or input ends. If interactive retry is required, recovery belongs inside a deliberate loop rather than after using an invalid value.
Range based for visits elements
A range-based loop says “for each element” without managing an index. Use const auto& for read-only access to elements that may be expensive to copy, and auto& only when the loop intentionally modifies them. A plain auto copies each element.
Index-based loops remain useful when the position is part of the output or neighboring elements are compared. Do not introduce an index solely from habit.
Quick knowledge check
Answer before you reveal.
01What three parts usually control a counted for loop?
Initialization, a continuation condition, and a progress update.
02Why is index <= size commonly wrong?
For zero-based sequences, size is one past the last valid index, so the usual condition is index < size.
Exercise
Practice challenge
Repeatedly read positive study-session minutes until the user enters 0, reject negative values, and print the number of sessions and total minutes.
Requirements
- Zero stops without being counted
- Negative values do not change the total
- Empty input produces a zero-session summary
Optional extension: Track and print the longest accepted session.
Open in C++ compilerLesson checkpoint
One small step locks it in
Mark this lesson complete, then keep the momentum going.
Clear up the details
Frequently asked questions
Is while true always bad?
No, but the exit path must be obvious and reachable. A direct sentinel condition is often clearer for beginner code.
Should I use break or change the loop condition?
Use a condition when it naturally describes continuation. A focused break can be clearer when the exit is discovered inside the body.
When should I use continue?
It can skip an invalid or irrelevant item, but several continue paths can hide progress updates and make the loop harder to audit.