04 Loops and Iteration
A practical guide to C++ loops, control-flow statements, iteration patterns, termination, and choosing the right loop for a task.
The three parts of reliable iteration
A loop repeatedly executes a body while a condition permits another iteration. Reliable iteration has three logical parts:
Initialization: establish the starting state.
Condition: determine whether another iteration should occur.
Progress: change state so that the condition can eventually become false.
The loop body may be a single statement or a compound statement enclosed in braces. Braces are a good default even for a one-statement body because they make later changes safer.
If no state relevant to the condition changes, the program may create an . For example, a counter-based loop must update its counter on every path that returns to the condition check.
Takeaway: Before writing a loop, identify its starting state, stopping condition, and progress step.
Pre-test and post-test loops
A checks its condition before executing the body. Consequently, it can execute zero times when the condition is false at the beginning.
A typical counting example initializes count, tests count <= 5, prints the current value, increments count, and then returns to the condition check. The increment is essential: without it, the condition could remain true indefinitely.
This loop type is also useful when the number of iterations is uncertain. For example, input can be read and processed while value != -1, where -1 is used as a stopping value. The input operation must occur before the next condition check so that the loop can make progress.
A reverses the order: it executes the body first and tests the condition afterward. This means its body always executes at least once. It is appropriate for menus and validation because the prompt or action occurs before the first test. In C++, the semicolon after the condition is required.
The key distinction is the minimum number of body executions: a while loop can execute zero times, whereas a do-while loop executes at least once.
Takeaway: Choose
whilewhen zero executions are possible and the condition must be checked first; choosedo-whilewhen one execution is guaranteed.
The and counting ranges
A places initialization, the continuation condition, and the update expression together in one header. Its execution order is:
Run initialization once.
Test the condition.
Execute the body when the condition is true.
Run the update expression.
Test the condition again.
For example, for (int i = 0; i < 5; ++i) prints the values from 0 through 4. The same behavior can be written with a while loop by initializing i before the loop, testing i < 5, and incrementing i in the body.
A variable declared in the initialization section normally has scope limited to the loop. After for (int i = 0; i < 3; ++i) finishes, i is not available outside that loop.
Use a when the task naturally counts through a known range. For zero-based positions, a condition such as i < limit excludes the endpoint, while i <= limit includes the endpoint. Omitting the condition creates a loop whose condition behaves like true, so an explicit termination path such as break or return is then required.
Takeaway: A is the compact form for initialization, testing, and progress when those steps form a clear counting pattern.
Control flow and common iteration patterns
Loop control statements refine normal flow without replacing the need for a clear termination design.
A immediately leaves the innermost enclosing loop and transfers control to the first statement after it. A common use is stopping a search once the target is found. If a loop prints values from 1 through 10 but uses break when i == 6, the output contains 1 2 3 4 5. In nested loops, break exits only the inner loop.
A skips the rest of the current iteration. In a for loop, control moves to the update expression before the condition is checked again. For example, testing number % 2 == 0 and then using continue skips even numbers while allowing the update to occur. In a while loop, place the progress update before a possible continue; otherwise, the skipped path may fail to change the condition and create an .
Common iteration patterns include:
Counting: repeat a known number of times with a counter.
Accumulation: update an during each relevant iteration.
Searching: track a result or flag and stop when the desired value is found.
-controlled input: process values until a special stopping value appears.
Validation and retry: request input repeatedly until it satisfies a condition.
Nested iteration: combine an outer and inner loop for grids, tables, or combinations.
For a rectangular grid with rows and columns, the inner body of a executes times.
A useful selection rule is to use while when the number of iterations is uncertain and the condition should be tested first, do-while when the body must run at least once, and for when initialization, termination, and progress form a counting pattern.
Takeaway: Use
breakto stop early andcontinueto skip deliberately, while preserving reliable progress toward termination.
Choosing and checking a loop
A loop should make clear how it starts, how it continues, and how it ends. Initialize loop-control variables before they are used, keep the condition understandable, and ensure that every relevant path makes progress toward termination.
An should generally be initialized before the loop and updated during every relevant iteration. In -controlled input, choose a that cannot be confused with valid data, or use another termination mechanism such as end-of-file or a separate count.
An is not automatically an error: it can be intentional when it contains a reliable exit such as break or return. However, a loop with no condition change and no reachable exit will not terminate.
When loops are nested, remember that the inner loop completes its iterations for each iteration of the outer loop. For a rectangular grid, this produces executions of the inner body.
Takeaway: Select the loop form that matches the task, then verify initialization, condition checks, progress, scope, and every termination path.