Curriculum

Curriculum

Spot Why a Loop Never Stops

Scenario

A lab equipment loan desk checks unreturnedKits while unreturnedKits > 0. Compare Plan A (subtracts 1 per return) against Plan B (adds 1 or leaves unreturnedKits unchanged).

Selected choicePick a choice below
Result—

Try it yourself

Before comparing, predict what happens to unreturnedKits = 3 if the update step adds 1 instead of subtracting 1.

Reveal the explanation
  1. unreturnedKits = 3, step = -1

    Stops after 3 passes (3 -> 2 -> 1 -> 0)

  2. unreturnedKits = 3, step = +1

    Infinite loop risk (3 -> 4 -> 5 -> ...)

  3. unreturnedKits = 3, step = 0

    Infinite loop risk (3 -> 3 -> 3 -> ...)

To verify a loop stops, check two things together: the stop condition and the update direction. A safe loop strictly shrinks the distance to the stop boundary on every pass.

Download shared test cases

Your turn

Compare two event waitlist loops starting at seatsNeeded = 4 while seatsNeeded > 0: Loop X sets seatsNeeded = seatsNeeded - 1; Loop Y checks seatsNeeded > 0 and prints a reminder without updating seatsNeeded. Explain which one terminates and why.

Common mistake Checking only the while condition and forgetting to verify that the loop body actually updates the tested variable toward the stop value.

Check your work

Identification that Loop X terminates in 4 passes (4 -> 3 -> 2 -> 1 -> 0) while Loop Y loops forever because seatsNeeded stays 4.

Quick check

A lab loan loop runs while kitsLeft > 0, starting at kitsLeft = 2. Which loop body creates an infinite loop?
Show the answer and reasoning

Correct answer kitsLeft = kitsLeft + 1

Adding 1 turns 2 into 3, 4, 5, and so on, moving away from 0 so kitsLeft > 0 never becomes false.