Fibonacci sequence are the numbers in the following integer sequence:
0,1,1,2,3,5,8,13,.........................
Fn=Fn-1+fn-2
High Level Language Code (Iterative version)
int i = 0, j = 1, k, t;
for (k = 1; k <= n; k++) // n is the number inserted by a user
{
t = i + j;
i = j;
j = t;
}
Algorithm
1. Get a number from a user
2. Print F0 and F1
3. Calculate Fn and print it (Hint: by using Loop until reach n)
4. End
Note that, it assumes the user will enter 2 or more for simplicity.
Output
Should be something like the following
0, 1, 1, … , n
Convert into assembly language
.data
hello_msg1: .asciiz "please enter number n !\n";
hello_msg3: .asciiz " !\n The ----- value ";
hello_msg4: .asciiz " !\n your program is finish ";
#-------------------------------------------------------------
.text
main:
add $t0,$zero,$zero
add $t2,$zero,$zero
add $t4,$zero,$zero
#-------------------------------------------------------------
la $a0, hello_msg1
li $v0, 4
syscall
#-------------------------------------------------------------
li $v0, 5 # Read integer n
syscall # $v0 = value read
#-------------------------------------------------------------
move $t0, $v0 #
#-------------------------------------------------------------
add $t3,$zero,$zero # i=0
addi $t4,$t4,1 # k=1
#-------------------------------------------------------------
la $a0, hello_msg3
li $v0, 4
syscall
#-------------------------------------------------------------
move $v0,$t2 # print 0
move $a0, $v0
li $v0,1
syscall
#----------------------------------------
la $a0, hello_msg3
li $v0, 4
syscall
#-------------------------------------------------------------
move $v0,$t4 # print 1
move $a0, $v0
li $v0,1
syscall
#----------------------------------------
loop:
add $t2,$t3,$t4 # t = i + j
slt $t5,$t0,$t2 # if $t2 >=$t0 then $t5=1 else $t5=0
bne $t5,$zero,L1 # if $t5=0 Exit program
#-------------------------------------------------------------
la $a0, hello_msg3
li $v0, 4
syscall
move $v0,$t2
move $a0, $v0
#-------------------------------------------------------------
li $v0,1
syscall
#-------------------------------------------------------------
add $t3,$t4,$zero # i = j
add $t4,$t2,$zero # j = t
j loop
#-------------------------------------------------------------
L1:
#-------------------------------------------------------------
la $a0, hello_msg4
li $v0, 4
syscall
#-------------------------------------------------------------
li $v0, 10 # Exit program
syscall