Fibonacci Sequence
Compute the first Fibonacci numbers using a loop. Each number is the sum of the two before it - a classic algorithm exercise at the register level.
The Fibonacci sequence (0, 1, 1, 2, 3, 5, 8, 13, 21...) is computed by keeping two running values and repeatedly summing them. In assembly, this requires careful use of registers as temporary storage — you need a third register to hold one value while you overwrite the other. This simulation shows how a simple algorithm translates to register-level operations with no abstraction to hide behind.
Simulator
Walkthrough Guide
- 1
Initialise the sequence
Do this: Step through the three MOV instructions
Watch for: R0 = 0 (previous), R1 = 1 (current), R3 = 7 (loop counter)
Fibonacci starts with 0 and 1. R0 holds the 'previous' value and R1 holds 'current'. R3 counts how many iterations remain.
- 2
First iteration: save, add, shift
Do this: Step through MOV R2, R1 / ADD R1, R0 / MOV R0, R2 / SUB R3, #1 / JNZ fib
Watch for: R2 saves 1, R1 becomes 1 (0+1), R0 becomes 1 (the old R1). Sequence so far: 0, 1, 1
The three-register dance: R2 saves current before it is overwritten, then current = current + previous, then previous = old current. Without the temporary register R2, we would lose a value.
- 3
Watch the sequence grow
Do this: Continue stepping or use Run at slow speed
Watch for: R0 and R1 evolve: (1,1) → (1,2) → (2,3) → (3,5) → (5,8) → (8,13) → (13,21)
Each iteration advances the sequence by one position. R3 counts down from 7, and when it hits 0 the loop exits.
- 4
Final result
Do this: Wait for HALT
Watch for: R1 = 21, R3 = 0
After 7 iterations R1 holds the 8th Fibonacci number (21). The algorithm used just 4 registers and a handful of instructions — this is as close to the metal as it gets.
Objectives
- •Watch R0 and R1 evolve through the Fibonacci sequence: 0,1 → 1,1 → 1,2 → 2,3 → 3,5 ...
- •See R2 act as a temporary register to swap values without losing data
- •Count the loop iterations using R3 as it decrements to zero
- •Verify R1 holds 21 when the program halts
Hints
- Each iteration computes next = current + previous, then shifts the window forward by one position