Write an assembly procedure to generate Fibonacci series. Fibonacci series is de
ID: 3631396 • Letter: W
Question
Write an assembly procedure to generate Fibonacci series. Fibonacci series is defined as bellow:0 1 1 2 3 5 8 13 21.....
F0 = 0, F1= 1, F2=1, F3=2, F4=3, …….. ,Fn = Fn_1 + Fn_2
You are not permitted to use recursive version. Your code must ask for a positive integer n from the input and call the Fibonacci function as bellow(code shows a sample non-recursive implementation, you can use your non-recursive implementation) :
Main()
{
// please enter a positive integer
// n is the value read from console
Fibonacci (n);
}
void Fibonacci(int n )
{
int fn_2 = 0;
int fn_1 = 1;
int fn = 0;
for( int i = 1; i < n; i++)
{ fn = fn_1 + fn_2;
printf("%d, ", fn);
fn_2 = fn_1;
fn_1 = fn;
}
Return;
}
Here is the sample program output:
Please enter n (This program generates 0 to Fn) : 5
0 1 1 2 3 5
Your program must handle errors. An error must be returned if n<0 and the maximum acceptable n is 20.
Please enter n : -2
Error! Enter a number greater than equal to 0.
Please enter n: 21
Error! Enter a number less than equal 20.
Explanation / Answer
.data
string1 .asciiz "Please enter n (This program generates 0 to Fn) :. " # declaration for string variable
main:
loop: li $v0, 4 # load appropriate system call code into register $v0;
# code for printing string is 4
la $a0, string1 # load address of string to be printed into $a0
syscall
li $v0, 5 # load appropriate system call code into register $v0;
# code for reading integer is 5
syscall # call operating system to perform operation
sw $v0, int_value # value read from keyboard returned in register $v0;
# store this in desired location
move $t0,$v0
blt $t0, 160, loop
li $t0, 10 # call Fibonacci(n)
jal Fibonacci
Fibonacci:
li $a0, 1 # Fib(n): parameter n
move $v0, $a0 # n < 2 => fib(n) = n
blt $a0, 2, done
li $t0, 0 # second last Fib’ number
li $a0, 1 # last Fib’ number
Fib: add $t1, $t0, $v0 # compute next Fib’ number in sequenceli $v0, 1 # system call code for print_int
la $a0, $t1 # address of int to print
syscall # print integer
move $t0, $v0 # update second last
move $v0, $t1 # update last
sub $a0, $a0, 1 # more work to do?
bgt $a0, 1, Fib # yes: iterate again
done: sw $v0, result # no: store result, done
.data
result: .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.