2.1.5 Repeating a Task With a Loop

Replace Repeated Statements with a Rule

A Zoo worker wants to prepare three food portions. Writing the same statement three times can produce the right result today, but changing the requested quantity means editing the code again. A loop keeps one copy of the work and repeats it while a condition remains true.

Start with Three Copies
A fixed three-portion demonstration
int preparedPortions = 0;
preparedPortions++;
preparedPortions++;
preparedPortions++;

This small model records one prepared portion per increment. It deliberately represents the operation with an integer so that you can focus on repetition before combining it with existing Food objects and methods.

The final count is 3, but the code does not describe a general stopping rule. Preparing five portions would require two more copies. A requested quantity held in a variable needs a different approach.

Give Repetition a Start and Stop
Express the Same Work as a Loop
One body, repeated as needed
int requestedPortions = 3;
int preparedPortions = 0;

while (preparedPortions < requestedPortions)
{
    preparedPortions++;
}

The starting state says that no portions are prepared. The condition asks whether work remains. The body records one more completed portion, then execution returns to the condition. One pass through the body is called an iteration.

For three requested portions, the body runs three times. Changing requestedPortions to 5 changes the amount of work without changing the loop's structure. Setting it to 0 makes the first condition false, so the body is skipped.

Follow One Full Cycle
Initialize preparedPortions to zero. While preparedPortions is below requestedPortions, prepare one portion and increase the count. When the condition is false, report the completed count.
Repeat until the requested count is reached
  • New
  • Changed
  • Removed

The action records one completed portion by increasing the count. The return edge is what turns the decision into repeated execution: after the update, the program asks the same question again using the new count.

Separate the Body from the Continuation

Work that should happen once per portion belongs inside the braces. Work that should happen once after all portions are prepared belongs after the loop. Moving a completion message into the body would display it after every portion.

The repeated action must also make progress. Here the counter moves toward requestedPortions. If nothing changes the condition's values, a true condition can stay true forever. Detailed loop debugging comes later; for now, identify the update whenever you read a loop.

Predict Before You Run
Change the Requested Work
Three requests
Requested portions Body executions Final prepared count
0 0 0
1 1 1
3 3 3

Cover the last two columns and predict them. Then explain why a condition is tested four times for a request of three even though only three portions are prepared. The final test confirms that no work remains.