2.1.6 while Loops

Repeat While Work Remains

A while loop checks its condition before each iteration. When the condition is true, its body runs; when the condition is false, execution continues after the loop. This fits work such as an airline counter serving passengers until no one remains waiting.

Read the Header and Braces
Model a small boarding queue
int waitingPassengers = 3;
int servedPassengers = 0;

while (waitingPassengers > 0)
{
    waitingPassengers--;
    servedPassengers++;
}

Console.WriteLine(servedPassengers);

The condition is waitingPassengers > 0. The two statements between the braces form the body. Each iteration records one passenger leaving the queue and one more passenger served. The display statement is outside the braces, so it runs after the repetition finishes.

This example uses counters to model the service operation. It does not require an array, list, or collection of Passenger objects. The changing counts are enough to explain the control flow.

Watch the State Change
Trace the Body and Final False Check
Queue trace
Check number Waiting before check Condition Served after body
1 3 True 1
2 2 True 2
3 1 True 3
4 0 False 3; body skipped

After the third body execution, waitingPassengers is 0. Execution still returns to the header, but the next check is false. The display then outputs 3. Reaching the bottom of the body is not itself a decision to stop.

While waitingPassengers is above zero, decrease waitingPassengers and increase servedPassengers, then return to the same condition. A false condition exits to display servedPassengers.
Check before each service cycle
  • New
  • Changed
  • Removed
A Body Can Execute Zero Times

If waitingPassengers starts at 0, the first check is false. Neither update runs, servedPassengers remains 0, and the final display still executes. A while loop never promises that its body will run once.

The start value and the comparison work together. Using waitingPassengers >= 0 would allow an extra iteration at zero and produce a negative waiting count. The intended rule is to serve a passenger only while at least one is waiting.

Keep the Repetition Controlled
Check the Update and Statement Boundaries

Both updates belong inside the braces. If the decrement were placed after the loop, waitingPassengers would stay at 3 throughout the repeated body. Also avoid a semicolon immediately after the while header: that would create an empty loop body before the braced statements.

As you read a while loop, point to the variable used in its condition and the statement that changes that variable. Then name the value that will make the next check false.

Explain Two Starting States

Trace the example with waitingPassengers set to 1, then to 0. State the number of body executions and the final values of both counters. Finally, explain what the program would do if only servedPassengers changed inside the body.