05. Iteration and Loops

A practical guide to designing, choosing, tracing, and testing loops, with emphasis on control flow, counting, accumulation, termination, and common errors.

The Loop Mental Model

means executing the same block of instructions repeatedly. A reliable loop coordinates three ideas:

  • Initialization establishes the starting state.

  • Condition determines whether another is allowed.

  • Update changes the state so that the loop can eventually terminate.

For example, a loop that processes values from a collection needs a way to identify the next value. A loop that validates input needs a condition describing what counts as invalid. A loop that counts repetitions needs a control variable that changes after each pass.

The central design question is: what changes from one to the next, and why must that change eventually make the condition false?

Takeaway: Every loop should have a clear purpose, a starting state, a continuation condition, useful work, and progress toward termination.

Choosing Between while and for

A checks its condition before each pass. If the condition is false initially, the body does not run at all. This makes it suitable for tasks such as repeatedly requesting input until a valid value is supplied.

A typical count-controlled pattern starts with a value, checks a boundary, performs the task, and then updates the controlling value. If the starting value is one and the loop continues while the value is at most five, the body processes five values: 11, 22, 33, 44, and 55. After the update, the value becomes 66, so the condition is false.

Use a while loop when repetition depends mainly on a changing condition or when the number of repetitions is unknown in advance. Always check that the update changes the variable used by the condition.

A is usually clearer when the program must visit each item in a sequence or repeat a known number of times. For example, traversing the letters in the word code processes c, o, d, and e in order.

In Python-like syntax, range uses an excluded stop value:

  • range(5) represents 00 through 44.

  • range(2, 7) represents 22 through 66.

  • range(10, 0, -2) represents 1010, 88, 66, 44, and 22.

Choose a when the sequence or count is explicit. Choose a when continuation depends on a condition that changes during execution.

Takeaway: Use condition-based repetition for while and collection- or count-based repetition for for.

Counters, Accumulators, and Sentinels

A answers a question such as “How many values satisfy this condition?” Initialize it before the loop, inspect each item, and increase it only when the relevant event occurs. To count even values, test whether the remainder after division by two is zero and increment the only for matching values.

An builds a result gradually. Its initial value must be appropriate for the operation:

  • A sum starts at 00.

  • A product starts at 11.

  • A concatenated string starts as an empty string.

  • A new list starts as an empty list.

To find a maximum, initialize the current maximum from the first available value, then compare later values against it. Replace the current maximum only when a larger value is found.

A supports input whose length is unknown. The program reads an initial value, checks whether it is the , processes it only if it is ordinary data, and then reads the next value. For example, if −1-1 is designated as the stopping value, it ends the loop but is not added to a running total.

The must not be confused with valid input. If every possible integer is valid data, use another termination method, such as a separate command or an end-of-input condition.

Takeaway: Counters count events, accumulators combine values, and sentinels separate ordinary input from the termination signal.

Nested Repetition and Loop Control

A places one loop inside another. The inner loop completes all of its iterations for every of the outer loop. Thus, an outer loop with 33 iterations and an inner loop with 44 iterations performs 3×4=123 \times 4 = 12 executions of the inner body.

Nested loops are useful for grids, tables, two-dimensional lists, and comparisons between pairs of values. A rectangle with three rows and five columns can be produced by rebuilding a line during each outer and adding five symbols during the inner .

When estimating work, multiply the approximate counts of independent nested loops. Two loops that each run approximately nn times perform approximately n2n^2 inner operations. This estimate helps identify loops that may become expensive as the input grows.

break immediately terminates the nearest enclosing loop. continue skips the remainder of the current and proceeds to the next one. In a nested structure, break exits only the innermost loop unless the language provides another mechanism for leaving multiple levels.

Takeaway: Nested loops multiply repeated work, while break and continue change the flow of the nearest loop and should be used deliberately.

Common Errors and Boundary Checks

Many loop failures come from a mismatch between the condition and the state update.

  • An occurs when the condition never becomes false. A common cause is forgetting to update the control variable.

  • An occurs when an endpoint is processed one time too many or too few. Remember that the stop value of range is excluded.

  • Incorrect initialization gives a or an unexplained starting value.

  • Updating the wrong variable leaves the condition unchanged, even if another variable changes.

  • Modifying a collection while iterating over that same collection can skip elements or process them unexpectedly. A safer approach is to iterate over a copy or construct a new collection.

  • Incorrect indentation or block boundaries can place statements inside or outside the loop unintentionally.

  • A loop such as while True needs a deliberate and guaranteed exit path.

Before writing a loop, identify the first value processed, the last value processed, whether the endpoint is included, and the amount by which the control state changes.

Takeaway: Most loop errors can be found by tracing the condition, the controlling state, the endpoint rules, and the exact boundary of the loop body.

Designing and Testing Correct Loops

A disciplined design process makes loop behavior easier to explain and test:

  1. State the repeated task in one sentence.

  2. Choose a for a known sequence or count, or a for condition-based repetition.

  3. Initialize every , , and control variable.

  4. Write the condition precisely.

  5. Process one item or one step in a focused loop body.

  6. Update the state that controls the condition.

  7. Test empty input, one item, the first valid value, the last valid value, and invalid input.

A provides a concise correctness check. For a loop that counts positive values, an appropriate invariant is: “The count equals the number of positive values examined so far.” It is true before processing any values, remains true after each value is processed, and describes the final result when the loop ends.

For a loop that sums values, a similar invariant is: “The total equals the sum of all values examined so far.” Such statements help reveal incorrect initialization, skipped items, and updates that occur at the wrong time.

When tracing a loop, record the control state and important results after each . Stop when the condition becomes false, and verify that the final result matches the intended boundary behavior.

Takeaway: A correct loop is not merely one that produces a result on one example; it has explicit state, predictable progress, tested boundaries, and a fact that remains true throughout execution.