Computer Science / Unit 4 CS 0190 worked example, 60 to 90 seconds
Tracing a Loop to Its Floor
The idea
A loop trace executes an algorithm by hand, one step per line, tracking every variable at every pass — the ground-level skill for reading any imperative program honestly.
In practice
Compute the factorial of 4 with a loop: a product starts at 1 and a counter starts at 4. Pass one: the condition asks whether the counter is zero — no — so the product becomes 1 times 4, which is 4, and the counter drops to 3. Pass two: not zero; product 4 times 3 is 12; counter 2. Pass three: product 12 times 2 is 24; counter 1. Pass four: product 24 times 1 stays 24; counter 0. Pass five: the condition finds zero and the loop ends — the product holds 24, and the trace shows every hand the value passed through. The same answer arrived by recursion in video 0057; here the machine's view did the walking: one condition, two variables, five checks.
Where people slip
A trace that skips a pass has proven nothing — the discipline is every line, every value.
Your place on the trail
Every lesson rests on earlier ones and opens later ones. Tap any to jump.
Builds on
Unlocks
Something wrong in this lesson? Flag it · Sources for Computer Science