SW StudyWalks

Computer Science  /  CS 0190  ·  Procedure · 60–90 seconds

Tracing a Loop to Its Floor

Video not yet published
to the StudyWalks catalog
State

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.

Show

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.

Watch for

A trace that skips a pass has proven nothing — the discipline is every line, every value.