2.2.7 Loop Initialization, Condition, and Update

Overview

To understand a counting loop, find its initial value, its continuation condition, and its update. These parts work together. A mistake in any one of them can skip all work, repeat an extra time, or prevent the loop from ending.

for (int count = 0; count < 3; count++)
{
    Console.WriteLine(count);
}
Identify Three Loop Parts
Activity diagram for loop initialization, condition, and update: identify three loop parts.
Identify Three Loop Parts
  • New
  • Changed
  • Removed

Initialization sets count to zero once. The condition is checked before each body pass. The update increases count after a pass. The display outputs 0, 1, and 2; count 3 fails the condition. A for loop collects these three pieces in its header.

The update does not run when the initial condition is already false. Record the condition result every time it is tested, including the final false result.

Trace the Outcome

Change only the initial value to 1 and predict the number of displays. Then restore it and change `< 3` to `<= 3`. Trace each change separately.