Teacher answer key

Algorithms with State

Gather four kinds of evidence: prediction of relevant state; behavior across varied cases including boundaries; explanation using trace/state evidence; and a reasoned correction of one mismatch. Mark each as emerging, with support or independent using paper or your school’s existing approved process. A challenge pass is machine-behavior evidence, not proof of authorship or complete mastery. Accept equivalent correct programs; the public key is a model, not the only possible answer.

Public teaching material. Solutions are examples; equivalent correct programs may also pass the actual checks.

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

Try prediction key

Output: 24

InstructionPC beforePC afterR0 beforeR0 afterRelevant stateOutput
LOAD0100{"registers":[0,4,0,0,0,0,0,0],"flags":{"zero":false,"negative":false,"overflow":false},"sp":255,"stack":[],"callStack":[],"loopStack":[],"memoryReads":[],"memoryWrites":[]}None
LOAD1200{"registers":[0,4,1,0,0,0,0,0],"flags":{"zero":false,"negative":false,"overflow":false},"sp":255,"stack":[],"callStack":[],"loopStack":[],"memoryReads":[],"memoryWrites":[]}None
LOOP2300{"registers":[0,4,1,0,0,0,0,0],"flags":{"zero":false,"negative":false,"overflow":false},"sp":255,"stack":[],"callStack":[],"loopStack":[{"start":2,"end":9,"remaining":4,"callDepth":0}],"memoryReads":[],"memoryWrites":[]}None

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

Example challenge solution

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

Actual checker fixtures

Case 1
Input
0
Initial memory
All bytes initially zero
Expected output
1
Case 2
Input
4
Initial memory
All bytes initially zero
Expected output
24
Case 3
Input
6
Initial memory
All bytes initially zero
Expected output
720

3. Explain the machine

Why does the product accumulator start at1?

Reasoning and teaching note

1 is multiplication's identity; zero iterations yield 0!=1. Starting0 would make every product0.