Student worksheet

Algorithms with State

Three lesson sections: predict, build, explain. Work on paper or in the local lab. No name, account or student record is requested by the app.

16. Factorial and Loop Invariants

Use a multiplicative accumulator and explain why 0! is 1.

Open this lesson →

1. Predict and trace

Before running the Try program, predict its output and trace the first three executed instructions. Track the relevant registers, flags or memory as needed. Then step the program to compare.

LOAD 4 R1
LOAD 1 R2
LOOP 4
LOAD R2
MUL R1
COPY R0 R2
LOAD R1
SUB 1
COPY R0 R1
RETURN
LOAD R2
PRINT
HALT

Queue input: None

Initialize memory: All bytes initially zero

InstructionPC beforePC afterR0 beforeR0 afterRelevant stateOutput
       
       
       

2. Build and check

Read N from 0 through 6 and print N!. Use a loop and a multiplication accumulator.

Required instruction types: INPUT, LOOP, MUL

Starter program

INPUT
COPY R0 R1
COPY R0 R3
LOAD 1 R2
LOOP R3
  # Multiply by factor; decrease factor.
RETURN
LOAD R2
PRINT
HALT

Your program and notes

3. Explain the machine

Why does the product accumulator start at1?