Example 1 — Trace the loop by hand
StandardProblem
n starts at 3, and while n is less than 20 the program doubles it. Count how many times the body runs, and give the value printed at the end.
Solution
-
Test before the first pass: 3 < 20 is true, so the body runs.
A while loop checks the condition first, so a loop whose condition starts false runs zero times.
-
Follow the back-edge: n becomes 6, then 12, then 24, with the test rerun after each doubling.
The arrow from the body back to the diamond is what makes this a loop. Every pass returns to the same test.
-
Stop on the first false test: 24 < 20 is false, so control takes the no branch to OUTPUT n.
The loop exits only when the test fails, which is always after the value has already crossed the limit.
Answer
The body runs 3 times (3 → 6 → 12 → 24) and the program prints 24.
Takeaway: The printed value has already passed the limit, because the test that stops the loop is the one that failed.