################################################################ ## int factorial(int n) ## ## { ## ## if (n < 1) ## ## return 1; ## ## ## ## return n * factorial(n - 1); ## ## } ## ################################################################ .text li $a0, 3 # n (do not use values of n > 10) jal factorial # call the recursive function. move $a0,$v0 # get result li $v0,1 # print integer syscall li $v0,10 syscall factorial: addi $sp,$sp,-4 # push the return address sw $ra,0($sp) addi $sp,$sp,-4 # push the value n sw $a0,0($sp) slti $t0, $a0, 1 # if (n < 1) $t0 = 1; else $t0 = 0. beq $t0, $zero, recurse # if ($t0 == 0) recurse # the next three lines are the base case: addi $v0, $zero, 1 # $v0 = 1. addi $sp, $sp, 8 # pop two words from the stack. jr $ra # return $v0. # the recursive case: recurse: addi $a0, $a0, -1 # n--. jal factorial # call factorial(n - 1). #this is where the recursive calls return: lw $a0,0($sp) # pop n from the stack. addi $sp,$sp,4 lw $ra,0($sp) # pop the return address addi $sp,$sp,4 # you'll learn about the multiply instruction soon: mul $v0, $a0, $v0 # $v0 = n * factorial(n - 1). jr $ra # return $v0. exit: