Created
January 4, 2017 18:59
-
-
Save lucasrpb/685885341ae48ed9e121010b04b92781 to your computer and use it in GitHub Desktop.
MIPS Assembly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.data ## Data declaration section | |
## String to be printed: | |
prompt: .asciiz "Enter a non-negative number:\n" | |
result: .asciiz "\nThe factorial is: " | |
.text | |
main: | |
li $v0, 4 | |
la $a0, prompt | |
syscall | |
li $v0,5 #Read the number(n) | |
syscall | |
move $a1, $v0 # n to $t2 | |
jal fact #perform the calculation | |
li $v0, 4 | |
la $a0, result | |
syscall | |
li $v0, 1 # service 1 is print integer | |
move $a0, $v1 # load desired value into argument register $a0, using pseudo-op | |
syscall | |
li $v0, 10 # end program | |
syscall | |
fact: | |
bgt $a1, 1, fatcr #factorial case | |
#base case | |
move $v1, $a1 # $v1 is the temp val holding the previous calculation | |
jr $ra | |
fatcr: | |
sub $sp, $sp, 8 #allocate space in the stack to save return addresses and function parameters | |
sw $ra, , 0($sp) #save return address | |
sw $a1, 4($sp) #save n | |
add $a1, $a1, -1 # decrement n to pass to the next function call | |
jal fact #perform the recursion call | |
lw $a1, 4($sp) #restore n | |
mul $v1, $a1, $v1 # n * fact(n-1) | |
lw $ra, 0($sp) #restore return address | |
add $sp, $sp, 8 #clean up the stack | |
jr $ra | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment