Answer to Question #292568 in Assembler for humn

Question #292568

write an Assembly language based program for MIPS Architecture based MARS simulator to find the Factorial of 10

1
Expert's answer
2022-01-31T16:18:12-0500
# 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  

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS