Trace a Loop That Runs Zero Times
Scenario
A library checkout kiosk loops while remainingBooks > 0: it scans one book and subtracts 1 from remainingBooks. What happens when a student taps Checkout with an empty cart?
Try it yourself
Before tracing, predict how many books the scanner will beep for when remainingBooks starts at 0.
| Case | Result |
|---|---|
| remainingBooks = 2 | Select a choice above to see what happens. |
| remainingBooks = 0 | Select a choice above to see what happens. |
| remainingBooks = -1 | Select a choice above to see what happens. |
Reveal the explanation
- remainingBooks = 2
2 passes, final remainingBooks = 0
- remainingBooks = 0
0 passes, final remainingBooks = 0
- remainingBooks = -1
Invalid input rejected before loop
Checking the condition before entering the loop protects against acting on empty data. Zero is a normal boundary value, not an error, and a pretest loop handles it cleanly with 0 passes.
Download shared test cases
Your turn
Trace the study-room booking waitlist loop: while pendingGuests > 0, send one seat alert and subtract 1. Record the pass count for pendingGuests = 0 and pendingGuests = 1.
Common mistake Assuming every loop runs at least once and forcing one extra scan or alert when the starting count is 0.
Check your work
A trace showing 0 > 0 evaluates to false on the first check (0 alerts sent) and 1 > 0 runs once before stopping (1 alert sent).
Quick check
This browser could not save your progress. Changes last until you leave the page.