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
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?
17. The Fibonacci Sequence
Keep two previous values and update them in a safe order.
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 1 R1
LOAD 1 R2
LOOP 8
LOAD R1
PRINT
ADD R2
COPY R2 R1
COPY R0 R2
RETURN
HALT
Queue input: None
Initialize memory: All bytes initially zero
2. Build and check
Read N from 0 through 8. Print the first N Fibonacci values, starting 1, 1. Print nothing for N = 0.
Required instruction types: INPUT, LOOP, ADD, COPY
Starter program
INPUT
COPY R0 R4
LOAD 1 R1
LOAD 1 R2
LOOP R4
# Print current; calculate and move the pair forward.
RETURN
HALT
Your program and notes
3. Explain the machine
Why can replacing the first prior value too early break Fibonacci?
18. Reverse a Memory Buffer
Copy a buffer backward using source and destination pointers.
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.
STORE 1 0
STORE 2 1
STORE 3 2
STORE 4 3
LOAD 3 R1
LOAD 16 R2
LOOP 4
LOAD [R1]
STORE R2
LOAD R1
SUB 1
COPY R0 R1
LOAD R2
ADD 1
COPY R0 R2
RETURN
HALT
Queue input: None
Initialize memory: 0: 1, 1: 2, 2: 3, 3: 4
2. Build and check
Four bytes are seeded at addresses 0–3. Copy them in reverse order into addresses 16–19, leaving the originals unchanged. Use a loop and register addresses; no output is required.
Required instruction types: LOOP, LOAD, STORE
Starter program
LOAD 3 R1
LOAD 16 R2
LOOP 4
# Read through R1, write through R2, move both pointers.
RETURN
HALT
Your program and notes
3. Explain the machine
Is this an in-place reversal? What must remain unchanged?