2.2.21 Choosing and Designing a Loop

Overview

Before writing a loop, identify what repeats, what stops it, and what state changes. If you are visiting an array of known length, an index bounded by Length is a clear plan. If the stop depends on a changing condition, a while loop may express it directly.

int i = 0;
while (i < values.Length)
{
    Process(values[i]);
    i++;
}
Plan the Repetition
Activity diagram for choosing and designing a loop: plan the repetition.
Plan the Repetition
  • New
  • Changed
  • Removed

The starting index is zero, the condition prevents an invalid access, the body processes the current item, and the update advances to the next position. The same design could use a for header without changing the visited elements.

Choose meaningful variable names and write the expected first and last iterations. This small trace makes the stopping boundary visible before a debugger run.

Trace the Outcome

Describe what would happen if values were empty, the update were omitted, or the condition used `<=`. Fix each issue in the plan before coding.