How does the four-step loop-variable pattern — initialize, test, use, change — turn a `while` loop into a factorial machine?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
The accumulator total = 0 and the loop variable i = 1 are given.
Use a while loop to add up the whole numbers 1, 2, 3, 4, 5, leaving the result in total. Follow the four-step pattern: initialize a loop variable, test it, use it, change it.
The four-step loop-variable pattern
Write the pattern as initialize the variable before the loop, test it in the condition, use it in the body, and change it each iteration, with the n < 5 skeleton.
Factorial as a running product
Write the factorial program with x = 4, factorial = 1 and i = 1, and trace each pass, listing factorial and i after every iteration up to the result 24.
Augmented assignment shorthand
Record that i += 1 rewrites i = i + 1 and fact *= 2 rewrites fact = fact * 2, then rewrite the factorial body in this form.