From the free course AP Computer Science A on Lykke

2.7 while Loops

Key concepts: while-loop syntax and condition evaluation · compound loop conditions using && and || · counter-controlled loops · sentinel conditions and loop termination · updating loop-control variables · simulating repeated days with a while loop · returning the number of completed iterations · accumulating values while traversing a 2D array · updating row and column positions from a Location · avoiding skipped elements when shifting items during traversal

A Java while loop repeats a block of code as long as its Boolean condition remains true. Unlike a for loop, which places initialization, continuation, and update expressions together, a while loop makes the stopping logic explicit—useful when repetition depends on a changing resource, a sentinel value, or a…

2.7 while Loops

A Java while loop repeats a block of code as long as its Boolean condition remains true. Unlike a for loop, which places initialization, continuation, and update expressions together, a while loop makes the stopping logic explicit—useful when repetition depends on a changing resource, a sentinel value, or a location moving through a structure.

Topic 2.7 — while Loops: A while loop evaluates its condition before every iteration. If the condition is false initially, the body executes zero times.

The loop’s control pattern

A reliable while loop has four visible parts:

initialize loop-control variables;

while (condition) {
    perform one repetition;
    update loop-control variables;
}

The loop-control variable is the value that eventually changes the condition from true to false. If no control value changes, the loop may never terminate.

Worked example: simulating feeding days

Suppose currentFood stores the amount of food left, numDays is the maximum number of days to simulate, and simulateOneDay(numBirds) removes one day’s food. The simulation should stop either when the feeder is empty or when the requested number of days has been completed.

public int simulateManyDays(int numBirds, int numDays) {
    int daysSoFar = 0;

    while (currentFood > 0 && daysSoFar < numDays) {
        simulateOneDay(numBirds);
        daysSoFar++;
    }

    return daysSoFar;
}

The loop continues only while both facts are true:

  • currentFood > 0: food remains.
  • daysSoFar < numDays: the day limit has not been reached.

The variable daysSoFar starts at $0$, the method simulates one day inside the loop, increments the counter, and returns the number of completed days after termination.

Key distinction: A loop can terminate because a counter reaches a limit, because a resource condition becomes false, or because either event occurs first.

Compound conditions: && versus ||

The operator in a compound condition determines the stopping rule. With &&, every required condition must remain true. With ||, the loop continues if at least one condition remains true.

while (currentFood > 0 && daysSoFar < numDays) {
    // Stop as soon as either condition becomes false
}

For a grid path, the loop should continue until both the final row and final column have been reached. Therefore, the continuation condition uses ||:

while (row < grid.length - 1 || col < grid[0].length - 1) {
    sum += grid[row][col];

    Location loc = getNextLoc(row, col);
    row = loc.getRow();
    col = loc.getCol();
}

return sum + grid[row][col];

Here, the body processes every position before the final position. After the loop, grid[row][col] is added separately because the loop condition is now false only when neither coordinate can advance.

Misconception check: choosing the wrong operator

Replacing || with && in the grid loop would stop too early: the loop would end as soon as either coordinate reached its final index, even if the other coordinate still needed to change. Conversely, using || when both conditions must be true can allow the loop to continue after one required condition has failed.

Sentinel-controlled loops

A sentinel is a special value that signals “stop.” It is not ordinary data and should not be processed as part of the input.

int value = input.nextInt();

while (value != -1) {
    process(value);
    value = input.nextInt();
}

The first value is tested before processing. Each iteration obtains a new value, so the loop eventually encounters $-1$ and terminates. Forgetting the update repeatedly tests the same value and creates an infinite loop; processing -1 inside the body incorrectly treats the sentinel as real data.

Traversal, searching, and safe updates

A search loop must examine the entire relevant range. It should return true immediately when a match is found, but return false only after the loop finishes without finding one.

int index = 0;

while (index < values.length) {
    if (values[index] == target) {
        return true;
    }
    index++;
}

return false;

When a loop changes the structure it traverses, its update must account for that change. For example, removing an element shifts later elements left; advancing immediately afterward can skip the element that moved into the current position. The general rule is to trace both the data movement and the loop-control update.

Retrieval check

A loop uses while (value != -1) to process input. If the first value is -1, how many times does the body execute, and why? In the feeding simulation, what two events can make while (currentFood > 0 && daysSoFar < numDays) stop? Finally, why does the grid-path loop use || rather than &&?

Answers: The sentinel loop executes zero times because its condition is false before the first iteration. The feeding loop stops when food reaches zero or the day limit is reached. The grid loop uses || so it continues while either the row or column still has not reached its final position.

2.7 while Loops - AP Computer Science A - image 1
2.7 while Loops - AP Computer Science A - image 1
2.7 while Loops - AP Computer Science A - image 2
2.7 while Loops - AP Computer Science A - image 2
2.7 while Loops - AP Computer Science A - diagram 1
2.7 while Loops - AP Computer Science A - diagram 1

Source Materials

The whole course on Lykke · Browse all public course wikis