4 Repetition and Looping
Learn how to design, select, control, and troubleshoot C++ loops for counted repetition, input validation, searching, accumulation, and multidimensional data.
Designing a terminating loop
A loop repeats a block of statements while a continuation condition permits it. Before writing one, identify three parts:
Initial state: the values before the first test.
Continuation condition: the rule that allows another iteration.
Progress step: the change that moves execution toward termination.
If the progress step is missing or cannot make the condition false, the program may enter an unintended infinite loop. A good loop makes all three parts easy to locate and understand.
Takeaway: Every loop needs a starting state, a test, and progress toward an ending state.
Choosing among C++ loop statements
Choose the loop form that matches when the condition should be tested and how repetition progresses.
while loop
A tests its condition before the body. It is appropriate when the number of repetitions is unknown or when the body may need to run zero times. For example, an input-validation loop can repeatedly request a number until the value lies in the permitted range.
A typical counter-based pattern prints values from through : initialize count to , continue while count <= 5, print the value, and increment count. The increment is essential because leaving count unchanged would preserve the same condition forever.
do-while loop
A runs its body before testing the condition, so it always runs at least once. Use it for menus or prompts that must be displayed before asking whether the user wants to continue. Remember the semicolon after the condition in the C++ syntax.
for loop
A is well suited to counted repetition. Its execution order is:
Run initialization once.
Test the condition.
Run the body if the condition is true.
Run the update expression.
Return to the condition test.
For example, initializing i to , continuing while , and incrementing i prints through . The counter declared in the initialization normally exists only within the loop and its body.
The initialization, condition, and update expressions are individually optional, but omitting the condition creates a loop that needs an explicit exit such as break or return.
Takeaway: Use while for a pre-tested condition, do-while when one execution is required, and for when initialization, testing, and progression form a natural counting pattern.
Controlling iterations with break and continue
A ends the nearest enclosing loop immediately. It is useful when a search finds the first matching item or when processing can stop as soon as a desired result is known. For example, a loop can search an array, store the matching index, and use a starting value of to indicate that no match was found.
A skips the rest of the current iteration and begins the next one. It is useful for filtering: a loop can continue when a value is even and therefore print only odd values. In a for loop, the update expression runs before the next condition test. In a while loop, perform the required update before continue; otherwise, the controlling variable may never change.
Both statements affect only the nearest enclosing loop. In nested loops, a break inside the inner loop exits the inner loop, not the outer one.
Takeaway: Use break for a clear early exit and continue for a clear skip, while preserving the progress needed for termination.
Working with nested loops
A places one loop inside another. For every iteration of the outer loop, the inner loop normally completes all of its iterations. This structure is useful for grids, tables, two-dimensional arrays, and comparisons of pairs of values.
If the outer loop runs times and the inner loop runs times for each outer iteration, the body executes times. For instance, an outer loop over rows from through and an inner loop over columns from through visits twelve row-column positions.
A break in the inner loop exits only that inner loop. To stop several levels, use a Boolean flag, return from the function, or restructure the algorithm so the control flow remains understandable.
Takeaway: Nested loops multiply work across levels, so track both the outer and inner bounds.
Common iteration patterns
Many loop tasks follow reusable patterns.
Accumulation: Initialize a running result before the loop and update it once per iteration, such as adding each value to a total.
Counting matches: Start a counter at zero and increment it whenever an item satisfies a condition.
Finding a maximum: Initialize the best value from a valid element, then compare later elements against it. This requires a separate design for an empty collection.
-controlled input: Read values while input succeeds and the value is not the . The signals termination and is not included in the total.
Index traversal: Use an index when the position is needed or elements must be modified. For a collection of
sizeelements, the usual condition is , keeping indexes in the valid range from through \.Direct value traversal: Use a range-based
forloop when the index is unnecessary. Use a reference to modify original elements and aconstreference to avoid copying while preventing modification.
These patterns turn a broad problem into a loop with a known initialization, test, update, and result-handling strategy.
Takeaway: Identify whether the loop is accumulating, counting, searching, selecting an extreme, reading until a , or traversing elements.
Avoiding common loop errors
Check loop boundaries and control flow deliberately.
An often comes from including one position too many. For a zero-based collection with
sizeelements, use , not , when visiting valid indexes.A missing update can keep the condition true indefinitely. Trace the controlling value through at least one complete iteration.
A stray semicolon after a loop condition can create an accidental empty loop, as in
while (ready());.In a
whileloop, place progress beforecontinuewhen the update would otherwise be skipped.Prefer a condition that directly expresses normal termination. Use
breakandcontinuewhen they clarify a search, filter, or early-exit operation rather than obscuring the main rule.Be careful with unsigned reverse loops. An unsigned index cannot become negative, so a condition that asks it to remain greater than or equal to zero may never become false. Use a signed index or another reverse-traversal strategy.
A practical review is to identify the initial value, evaluate the first condition, follow one update, and verify that the loop eventually reaches a false condition or an explicit exit.
Takeaway: Most loop bugs occur at boundaries, updates, or control transfers; inspect those points first.