2.1.6 while Loops

Check Before Each Soccer Training Turn

Three Wildcats players are waiting for a practice turn. A while loop can record a completed turn and reduce the waiting count until nobody remains. Assume the starting waiting count is nonnegative.

This is a counter model inside an existing method. It records completions without needing player objects, arrays, or input/output code.

Identify the Header and Body
Record the waiting players taking turns
int waitingPlayers = 3;
int completedTurns = 0;

while (waitingPlayers > 0)
{
    waitingPlayers = waitingPlayers - 1;
    completedTurns = completedTurns + 1;
}
Read One Pass Slowly

The starting assignments store 3 waiting players and 0 completed turns. The condition waitingPlayers > 0 is checked before the body.

When it is true, the first assignment subtracts one from the waiting count. The second adds one to the completed count. Both statements belong inside the braces and execute once per pass. After them, execution returns to the condition.

When the condition becomes false, execution skips the whole body and continues after the closing brace. A statement placed after the loop would run once after repetition finishes.

Include the Last False Check
State through the loop
Check Waiting before test Condition Waiting after body or exit Completed after body or exit
1 3 true 2 1
2 2 true 1 2
3 1 true 0 3
4 0 false 0 3
Check Zero Work and Common Mistakes
Check Your Prediction