This week I’m working with branches and loops in the assembly language. Here is a program which works out the Fibonacci series. It was part of an exercise.
## fibo .text .globl main main: ori $8, $0, 0 # Previous ori $9, $0, 1 # Current ori $11, $0, 100 # Counter to 100 L1: beq $10, $11, exit # exit if counter is 100 add $9, $8, $9 # add previous to current ori $5, $9, 0 # sum add $10, $10, 1 # increment counter add $8, $9, $8 # add previous to new current ori $5, $8, 0 # sum add $10, $10, 1 # increment counter j L1 exit: j exit # sponge for excess cycles sll $0,$0,0 ## End of file
The program is supposed to exit when the series reaches its 100th number, but the assembly can’t reach that far. The beq statement simply checks if a register is equal to another in this example. If it is equal it is taken to the “exit” label located at the bottom of the program. If not the program continues per normal and jumps back to L1. Then the check is made again.
The comments above really are self-explanatory. As you can see, there are 2 main registers used for the calculations. One holds the “previous” ($8) number in the series, whilst the other register holds the “current” (9) value. Another ($5) is used to store the sum of these numbers. There are two occasions where the counter is updated, which is used to represent the sequence number of the number in the fibonacci series.
For those who can’t remember the Fibonacci series, its where the two previous numbers are added together, then this continues and continues like so…
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...