# /* # * factorial of n = 1 * 2 * 3 * ... * n (recursive_factorial.c) # */ # #include # # int factorial(int); # # void main() { # int n; # printf("\nEnter a number to find factorial: "); # scanf("%d", &n); # printf("Factorial of %d = %d\n", n, factorial(n)); # } # # int factorial(int n) { # if (n > 1) { # return n * factorial(n - 1); # } else { # return 1; # } # } # # factorial of n = 1 * 2 * 3 * ... * n (recursive_factorial_mips.s) # .data $LC0: .ascii "\nEnter a number to find factorial: " $LC1: .ascii "%d" $LC2: .ascii "Factorial of %d = %d\n" .text main: # entry of main() addi $sp, $sp, -20 # reserve stack space sw $31, 16($sp) # save return address sw $fp, 12($sp) # save $fp sw $16, 8($sp) # save $16 move $fp, $sp # new $fp lui $2, %hi($LC0) ori $4, $2, %lo($LC0) # printf(): $4: address of string to be printed out jal printf # printf("\nEnter a number to find factorial: "); lui $2, %hi($LC1) ori $4, $2, %lo($LC1) # scanf(): $4: address of "%d" addi $5, $fp, 4 # scanf(): $5: location to store inputted n jal scanf # scanf("%d", &n); lw $16, 4($fp) # $16: n, for late printf() lw $4, 4($fp) # factorial(): $4: n jal factorial # factorial(n); final_return_here: lui $4, %hi($LC2) ori $4, $4, %lo($LC2) # printf(): $4: address of string to be printed out move $5, $16 # printf(): $5: n move $6, $2 # printf(): $6 = factorial(n) ($2: product after call) jal printf # printf("Factorial of %d = %d\n", n, factorial(n)); move $sp, $fp # for restoring using $sp lw $16, 8($sp) # restore $16 lw $fp, 12($sp) # restore $fp lw $31, 16($sp) # restore return address addi $sp, $sp, 20 # release stack space jr $31 # return to OS factorial: # entry of factorial(n) addi $sp, $sp, -12 # reserve stack space sw $31, 8($sp) # save return address sw $fp, 4($sp) # save $fp move $fp, $sp # new $fp sw $4, 12($fp) # $4: n, save to memory at $fp + 24 lw $2, 12($fp) # $2: n slt $2, $2, 2 # if (n < 2) bne $2, $0, $L3 # jump to $L3 lw $2, 12($fp) # $2: n addi $2, $2, -1 # $2: n = n - 1 move $4, $2 # factorial(): $4: n jal factorial # factorial(n); recursive_return_here: move $3, $2 # $3 = factorial(n) ($2: product after call) lw $2, 12($fp) # $2: n mult $3, $2 # product = product * n mflo $2 # $2: product j $L4 # jump to $L4 $L3: addi $2, $0, 1 # for n = 1, return 1 $L4: move $sp, $fp # for restoring using $sp lw $fp, 4($sp) # restore $fp lw $31, 8($sp) # restore return address addi $sp, $sp, 12 # release stack space jr $31 # return from factorial .end