Curriculum

Curriculum

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?

Selected choicePick a choice below
Result—

Try it yourself

Before tracing, predict how many books the scanner will beep for when remainingBooks starts at 0.

Reveal the explanation
  1. remainingBooks = 2

    2 passes, final remainingBooks = 0

  2. remainingBooks = 0

    0 passes, final remainingBooks = 0

  3. 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

A library return bin starts with remainingBooks = 0. The rule says: while remainingBooks > 0, log one book and subtract 1. How many times does the log step run?
Show the answer and reasoning

Correct answer 0 times, because the condition is checked before the body and is already false

A pretest loop evaluates remainingBooks > 0 before running the body. Since 0 > 0 is false, the body runs 0 times.