Sample Solution for Porgramming Assignment
# This program computes factorial using tail call
#
# Input: n must be a positive integer
# Output: n!
#
# main program
# print prompt
# read n
# call fact(n,1)
# print the value of n!
# exit
#
.data
.align 2
# input prompt string
prmpt: .asciiz "\n\nEnter value for n: "
# output descriptor
descr: .asciiz "\nn! = "
.text
.align 2
.globl main
main:
# print prompt
li $v0, 4 # system service print_string
la $a0, prmpt # pass the string
syscall
# read n
li $v0, 5 # system service read_int
syscall # n is in $v0
# call fact(n, 1)
move $a0, $v0 # pass n, first arg.
li $a1, 1 # pass 1, second arg.
jal fact # call fact, result in $v0
# print result
move $s0, $v0 # move result to $s0
li $v0, 4 # system service print_string
la $a0, descr # pass the string
syscall
li $v0, 1 # system service print_int
move $a0, $s0 # pass the result
syscall
# exit
li $v0, 10 # system service exit
syscall
#
# C code:
#
# % fact(n,1) returns n! where n>0
# %
# int fact(int n, int prod) {
# if n == 1
# return prod;
# else
# fact(n-1, n*prod);
# }
#
# register usage:
# $a0 = n
# $a1 = prod
#
# side effect:
# $a0 and $a1 are changed on return
#
fact: li $t1, 1
bne $a0, $t1, factne1 # if $a0=1
move $v0, $a1 # return the second arg
jr $ra
factne1: # else
mul $a1, $a1, $a0 # $a1 = prod*n
addi $a0, $a0, -1 # $a0 = n - 1
j fact # tail call fact