write an Assembly language based program for MIPS Architecture based MARS simulator to find the Factorial of 10
# MARS
# MIPS
###############################################################
.data
Output: .asciiz "! = "
endP: .asciiz "\n\nEnd of program"
# code segment
.text
.globl main
main:
li $a0,10
li $v0, 1 # Print integer from $a0.
syscall
jal fact # jmp the Factorial Function.
# the input argument in register $a0
# Function "fact" returns the result in $v0.
add $t0, $v0, $zero # Move factorial result into register $t0
# display the result of the Factorial Function
li $v0, 4 # Print string
la $a0, Output # "! = "
syscall
add $a0, $t0, $zero # Move Factorial to $a0
li $v0, 1 # Print integer from $a0.
syscall
exitP: nop
li $v0, 4 # Print string
la $a0, endP # "End of program"
syscall
li $v0, 10 # finished .. stop .. return
syscall # make the syscall
##################################################
# function Factorial
# input argument in $a0
# result in $v0
##################################################
fact:
# base case
bgt $a0, 0, recurion # IF (n <= 0)
li $v0, 1 # $v0 = 1 (return register)
jr $ra # return
recurion: # ELSE
addi $sp, $sp, -8 # stack push (space for two words)
sw $a0, 4($sp) # save n to stack
sw $ra, 0($sp) # save $ra (return addr) to stack
addi $a0, $a0, -1 # (n – 1)
jal fact # v0 = factorial(n – 1)
addi $a0, $a0, 1 #next n
mul $v0, $v0, $a0 #n*(n-1)
lw $ra, 0($sp) # retun $ra from stack
lw $a0, 4($sp) # return n from stack
addi $sp, $sp, 8 # stack pop
jr $ra # return
Comments
Leave a comment