.globl __start
.rodata
msg1: .string "Enter a number (or negative number to quit): "
msg2: .string "The factorial of "
msg3: .string " is: "
msg4: .string "nDo you want to calculate another factorial (y/n)? "
.text
__start:
loop:
# Print prompt for user input
li a0, 4 # syscall for write string
la a1, msg1
ecall
# Get user input
li a0, 5 # syscall for read integer
ecall
mv x10, a0 # move input to register x10 (n)
# Check if negative (n < 0)
blt x10, x0, exit # branch less than (negative) to exit
# Print message "The factorial of "
li a0, 4 # syscall for write string
la a1, msg2
ecall
# Print the number before calculating factorial
li a0, 1 # syscall for write integer
mv a1, x10 # move n to print register
ecall
# Recursive call: fact(n)
mv a0, x10 # Move n to a0 for recursive call
jal ra, fact # call fact function with n
# Print message " is: "
li a0, 4 # syscall for write string
la a1, msg3
ecall
# Print the result (factorial)
li a0, 1 # syscall for write integer
mv a1, a0 # move result to print register
ecall
# Jump back to the beginning of the loop for another calculation
j loop
exit:
# Exit program
li a0, 10
ecall
fact: # recursive function for factorial
# Save return address (ra) and the argument (n) onto the stack
addi sp, sp, -16
SW ra, 12(sp) # Save return address
SW a0, 8(sp) # Save argument (n)
# Base case: if n = 0 or n = 1, return 1
beqz a0, end_fact
li t0, 1
beq a0, t0, end_fact
# Recursive case: fact(n-1)
addi a0, a0, -1 # Decrement n
jal ra, fact # Recursive call
lw t1, 8(sp) # Restore n
mul a0, a0, a1 # Multiply result by n
ret
end_fact:
# Return 1 for the base case (factorial of 0 or 1)
li a0, 1
ret
I want to make the code to repetitively executed to compute n! for different n’s. But when I type any number, it just still calculate the factorial of 1
I have tried to modify the code so that after the recursive call to fact(n-1)
, the result is moved back to x10
register for proper storage and later printing, and then after the recursive call to fact(n-1)
, the result is stored in register a1
and then multiplied by n
before returning
1