I can't seem to find where I am wrong in my algorithm, my specific problem is that i seem to print the same value for all integer inputted in the console: here is my code
main:
li $v0, 5
syscall
jal factorial
li $v0, 10
syscall
factorial:
###preamble###
subu $sp, $sp, 32
sw $ra, 28($sp)
sw $fp, 24($sp)
addu $fp, $sp, 32
sw $a0, 20($fp)
###preamble###
lw $v0, 20($fp)
bgtz $v0, multiply
li $v0, 1
j end
multiply:
lw $v1, 20($fp)
subu $v0, $v1, 1
move $a0, $v0
jal factorial
lw $v1, 20($fp)
li $t3, 0
li $t2, 1
b multi
multi:
beq $t2, $v0, endLOOP
add $t3, $t3, $v1
add $t2, $t2, 1
b multi
endLOOP:
move $v0, $t3
end:
lw $ra, 28($sp)
lw $fp, 24($sp)
addu $sp, $sp, 32
move $a0, $v0
li $v0, 1
syscall
jr $ra
in this code i always seem to print a value of 10 while here in my second code, i always get an 11
main:
li $v0, 5
syscall
jal factorial
li $v0, 10
syscall
factorial:
###preamble###
subu $sp, $sp, 32
sw $ra, 28($sp)
sw $a0, 24($sp)
li $v0, 1
ble $a0, $zero, end
b multiply
###preamble###
multiply:
addi $a0, $a0, -1
jal factorial
lw $a0, 24($sp)
b multi
multi:
beq $t2, $v0, endLOOP
add $t3, $t3, $a0
add $t2, $t2, 1
b multi
endLOOP:
move $v0, $t3
end:
lw $ra, 28($sp)
addu $sp, $sp, 32
move $a0, $v0
li $v0, 1
syscall
jr $ra
also, please note that we are not allowed to use the mult function so please dont ask why i am not using it. Thank you for your help :D
I see a couple of problems with your code:
li $v0, 5
syscall
jal factorial
syscall
5 (read_int
) will return the value in $v0
, so when you enter factorial
for the first time you'll have the argument in $v0
. You could fix that by moving the value to $a0
before the jal
.
li $v0, 1
syscall
jr $ra
Wouldn't this print make more sense outside of the factorial function? Since $v0
is supposed to hold the function's return value, consider what will happen when you return from factorial(2)
to factorial(3)
and you've overwritten $v0
with the value 1.