In this code I am using MIPS Assembly and I am trying to find the factorial of 3 using recursion. But my output is 4 when it should be 6. Here is my code below.
.data
result_str: .asciiz "Factorial of 3 = "
newline: .asciiz "n"
.text
.globl main
main:
# Calculates the factorial of 3
li $a0, 3
jal factorial
# Prints the result
li $v0, 4
la $a0, result_str
syscall
move $a0, $v0
li $v0, 1
syscall
# Prints a newline
li $v0, 4
la $a0, newline
syscall
# Exits program
li $v0, 10
syscall
factorial:
# Save return address
addi $sp, $sp, -8
sw $ra, 4($sp)
sw $s0, 0($sp)
# if n <= 1 return 1
li $t0, 1
ble $a0, $t0, base_case
addi $a0, $a0, -1 # save a0 to a new spot
jal factorial
move $s0, $v0
# Multiply
mul $v0, $a0, $s0
lw $ra, 4($sp)
lw $s0, 0($sp)
addi $sp, $sp, 8
jr $ra
base_case:
# If n <= 1 return 1
li $v0, 1
lw $ra, 4($sp)
lw $s0, 0($sp)
addi $sp, $sp, 8
jr $ra
I am not sure what is wrong with it I think there is an error in the factorial section of the code.
New contributor
Aiden Haley is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.