2.2.4 for Loops

Overview

A `for` loop places initialization, condition, and update in one header. It is useful when a counter follows a known range. An airline application can visit boarding groups numbered 1 through 3 without writing the same call three times.

for (int group = 1; group <= 3; group++)
{
    CheckBoardingGroup(group);
}
Count with a for Loop
Activity diagram for for loops: count with a for loop.
Count with a for Loop
  • New
  • Changed
  • Removed

The counter starts at 1. Before each pass, `group <= 3` is checked. The body runs for 1, 2, and 3; after each pass `group++` increases the counter. At 4 the condition is false, and execution continues after the loop.

The body can be skipped entirely if the initial value fails the condition. For example, starting group at 4 yields zero calls. The diagram expands the compact header into separate activities.

Trace the Outcome

Trace each condition check, including the final false check at group 4. Explain which part of the for header establishes the initial value and which part moves toward the stop.