# Implement a recursive factorial function. # # int fact (int n) # { # if (n < 1) # return (1); # else # return (n * fact (n - 1)); # } # #Stack Frame: # old $a0 argument # old $ra # old $fp fp points to top of saved registers, double word aligned # YKM March 12, 2008 .text .globl main # Subroutine fact expects argument in $a0, and leaves result in $v0 fact: subu $sp,$sp,12 # Stack frame is 12 bytes long sw $ra,4($sp) # Save return address sw $fp,0($sp) # Save frame pointer addiu $fp,$sp,8 # Set up frame pointer sw $a0,0($fp) # Save argument (n) lw $v0,0($fp) # Load n bgtz $v0,L2 # Branch if n > 0 li $v0,1 # Return 1 jr L1 # Jump to code to return L2: lw $v1,0($fp) # Load n subu $v0,$v1,1 # Compute n - 1 Lb: move $a0,$v0 # Move value to $a0 jal fact # Call factorial function lw $v1,0($fp) # Load n mul $v0,$v0,$v1 # Compute fact(n-1) * n L1: # Result is in $v0 lw $ra, 4($sp) # Restore $ra lw $fp, 0($sp) # Restore $fp addiu $sp, $sp, 12 # Pop stack jr $ra # Return to caller nop # for delayed branching main: la $a0, Prt # Prompt li $v0, 4 syscall li $v0, 5 # read integer n syscall move $a0, $v0 # To call fact jal fact # Call factorial function move $t0, $v0 # save result in $t0 la $a0, Res # print preamble li $v0, 4 syscall move $a0, $t0 # result in $a0 to print it li $v0, 1 syscall li $v0, 10 # exit syscall .data Prt: .asciiz "\n Type interger:" Res: .asciiz "\n It's factorial is:" # place breakpoint at Lb, watch the stack contents.