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).
Try it yourself
Before comparing, predict what happens to unreturnedKits = 3 if the update step adds 1 instead of subtracting 1.
| Case | Result |
|---|---|
| unreturnedKits = 3, step = -1 | Select a choice above to see what happens. |
| unreturnedKits = 3, step = +1 | Select a choice above to see what happens. |
| unreturnedKits = 3, step = 0 | Select a choice above to see what happens. |
Reveal the explanation
- unreturnedKits = 3, step = -1
Stops after 3 passes (3 -> 2 -> 1 -> 0)
- unreturnedKits = 3, step = +1
Infinite loop risk (3 -> 4 -> 5 -> ...)
- 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
This browser could not save your progress. Changes last until you leave the page.