int fib(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else {
ID: 3653341 • Letter: I
Question
int fib(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { return fib(n - 1) + fib(n - 2); } } void main() { int result = fib(8); }Explanation / Answer
fib: slti $t0, $a0, 2 # if i < 2 (i.e i == 1) beq $t0, $zero, cont # if i >= 2 go to cont addi $v0, $zero, 1 # else make the return value 1 jr $ra cont: # OPERATION 1: MAKE SPACE IN STACK addi $sp, $sp, -16 # make space for 3 elements in the stack sw $ra, 0($sp) # save the return address sw $a0, 4($sp) # OPERATION 2: RECURSIVE CALLS addi $a0, $a0, -1 # calculate n - 1 jal fib # calculate fib(n - 1) sw $v0, 8($sp) # save into the stack result of fib(n - 1) lw $a0, 4($sp) # load the value of n addi $a0, $a0, -2 # calculate n - 2 jal fib sw $v0, 12($sp) # save into the stack the result of fib(n - 2) # OPERATION 3: POP FROM STACK lw $ra, 0($sp) # load the return address lw $t0, 8($sp) # load the value of fib(n - 1) lw $t1, 12($sp) # load the value of fib(n - 2) addi $sp, $sp, 16 # pop from stack # OPERATION 4: OPEARATION add $v0, $t0, $t1 # fib(n - 1) + fib(n - 2) jr $raRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.