I'm trying to code this recursive function into MIPS.
My problem is I'm not sure how I can do the recursive step.
I'm pretty sure I got the rest correct.
int recur(int n) {
if(n == 1 || n == 2) {
return 2;
} else {
return (n-4)+n*recur(n-2);
}
}
.data
promptMessage: .asciiz "Enter a number that is greater than or equal to 0: "
resultMessage: .asciiz "\nThe answer is: "
input: .word 0
answer: .word 0
.text
.globl main
main:
#Read the number from the user
li $v0, 4
la $a0, promptMessage
syscall
li $v0, 5
syscall
sw $v0, input
#Call the function
lw $a0, input
jal recur
sw $v0, answer
#Display result
li $v0, 4
la $a0, resultMessage
syscall
li $v0, 1
lw $a0, answer
syscall
.globl recur
recur:
addi $sp, $sp, -8
sw $a0, 0($sp)
sw $ra, 4($sp)
#Base Case if(n == 0 || n == 1) return 2;
li $v0, 2
beq $a0, $zero, DONE
beq $a0, 1, DONE
#RECURSIVE STEP
addi $a0, $a0, -2
jal recur
You did a great job. Creating C code first. You were very close.
I had to add the calculation step and the function epilog code.
Also, there was a bug where after main prints the number, there was no syscall 10 (exit) so the code would just fall through and recurse infinitely.
I reworked the C code slightly so it would be more compatible with the MIPS code.
Just for fun, and ease of testing, I changed main to loop and reprompt until it gets a negative number.
I've cleaned up and tested the code, added annotations [please pardon the gratuitous style cleanup]: