Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

25 min

The while Loop

Use condition-based repetition

By the end of this lesson

  • Use condition-based repetition
  • Make progress toward a stopping condition

A condition determines when work stops

There are seven labels to print. A batch can contain at most three. Before coding, predict the batch sizes: 3, 3 and 1. Unlike a fixed repeated message, the remaining work changes after each batch.

let remainingLabels = 7;
let batches = 0;
while (remainingLabels > 0) {
  const batchSize = Math.min(3, remainingLabels);
  remainingLabels = remainingLabels - batchSize;
  batches++;
  console.log(batchSize);
}
console.assert(remainingLabels === 0);
console.assert(batches === 3);

Math.min returns the smallest supplied number. while checks its condition before every iteration. If no labels remain initially, the body never runs. A for loop could also express this; choose the form that makes the controlling condition clearest.

Guided review: the missing progress step

Removing the subtraction leaves remainingLabels at 7 forever. The condition stays true and the program cannot finish. Identify this error on paper; do not deliberately run the endless version in your browser. If a page becomes unresponsive during practice, reload or close that tab and fix the stopping logic before trying again.

Progress must move toward termination. Subtracting zero in every iteration would not help. A changing variable alone does not guarantee useful progress.

Independent exercise

Set the initial count to 0 and then 6. Predict the number of batches and final remainder. Then describe what should happen if the batch limit is zero.

Correction

Zero labels require zero batches; six labels require two batches; both end with zero remaining. A zero batch limit should be rejected before the loop, because no iteration could reduce the work. This is a precondition: a fact the algorithm relies on.

Review

For your loop, state the quantity that decreases, its lower bound and the rule that ensures it actually decreases. This reasoning is more reliable than hoping the loop eventually stops.

Lesson complete?

Your progress is saved on this device.