2.1.5 Repeating a Task With a Loop

Repeat a Soccer Training Task

The Wildcats coach plans three practice turns. This small model records completed turns with a counter. Updating the counter represents finishing a turn; it does not make a player perform a real drill.

Start with Repeated Statements
Record exactly three completions
int completedTurns = 0;
completedTurns = completedTurns + 1;
completedTurns = completedTurns + 1;
completedTurns = completedTurns + 1;

The final count is 3. To record five turns this way, you would need two more copies. A loop keeps one copy of the repeated work and uses a rule to decide whether it should run again.

Give Repetition a Start and Stop
Repeat until the planned count is reached
int plannedTurns = 3;
int completedTurns = 0;

while (completedTurns < plannedTurns)
{
    completedTurns = completedTurns + 1;
}
Follow One Cycle

Start with 0 completed turns. Ask whether 0 is less than 3. Because the answer is true, record one completion, giving a count of 1. Go back to the same question with the updated count.

The next two passes change the count to 2 and then 3. The next question asks whether 3 is less than 3. It is false, so the body is skipped and repetition ends. The starting assignment happens once, before repetition begins.

Separate Checks from Body Executions
A plan of three turns
Completed before test Condition result Completed after body or exit
0 true 1
1 true 2
2 true 3
3 false 3; body skipped
Change the Requested Work

Assume planned turns is nonnegative. Changing plannedTurns changes how many completions are recorded without adding copies of the body.