I need help with the following MIPS machine assembly code question (translate fr
ID: 3585656 • Letter: I
Question
I need help with the following MIPS machine assembly code question (translate from C to MIPS machine assembly code):
Implement the following C code in MIPS assembly.
int verify (int n) {
if (n <= 2) {
return n;
else
return n –verify(n-1)*verify(n-2);
}
#SIMILAR PROBLEM BELOW:
Implement the following C code in MIPS assembly.
int square (int n) {
if (n <= 2) {
return n*n;
else
return n*n + square (n – 1)+square(n – 2);
}
fib: addi $sp, $sp, -12 # make room on stack
sw $ra, 8($sp) # push $ra
sw $s0, 4($sp) # push $s0
sw $a0, 0($sp) # push $a0 (N)
bgt $a0, $0, cont # if n>0, test if n=1
add $v0, $0, $0 # else fib(0) = 0
j rtn #
cont: addi $t0, $0, 1 #
bne $t0, $a0, cal # if n>1, gen
add $v0, $0, $t0 # else fib(1) = 1
j rtn
cal: subi $a0, $a0,1 # n-1
jal fib # call fib(n-1)
add $s0, $v0, $0 # copy fib(n-1)
sub $a0, $a0,1 # n-2
jal fib # call fib(n-2)
add $v0, $v0, $s0 # fib(n-1)+fib(n-2)
rtn: lw $a0, 0($sp) # pop $a0
lw $s0, 4($sp) # pop $s0
lw $ra, 8($sp) # pop $ra
addi $sp, $sp, 12 # restore sp
jr $ra
Explanation / Answer
Answer:
int verify (int n) {
if (n <= 2) {
return n;
else
return n –verify(n-1)*verify(n-2);
}
Mips code of above C program
(b) int square (int n) {
if (n <= 2) {
return n*n;
else
return n*n + square (n – 1)+square(n – 2);
}
MIPS code of the above code: