Last active
March 22, 2018 02:57
-
-
Save fellipecaetano/cb00fc57fefbda4e3622d915fde7656f to your computer and use it in GitHub Desktop.
Procedure that calculates the factorial of a number recursively, written in 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
.text | |
.globl main | |
main: | |
add $a0, $zero, 8 | |
jal fact | |
j exit | |
# int fact(int n) { | |
# if (n < 1) { | |
# return 1; | |
# } else { | |
# return n * fact(n - 1); | |
# } | |
# } | |
fact: | |
slti $t0, $a0, 1 | |
bne $t0, $zero, fact_early_return | |
# here n is greater than or equal to 1 | |
# we push $a0 (the original argument) and | |
# and $ra (the return address) onto the stack | |
addi $sp, $sp, -8 | |
sw $a0, 0($sp) | |
sw $ra, 4($sp) | |
# we call fact recursively with $a0 = n - 1 | |
addi $a0, $a0, -1 | |
jal fact | |
# we pop the original values for $a0 and $ra from | |
# the stack | |
lw $ra, 4($sp) | |
lw $a0, 0($sp) | |
addi $sp, $sp, 8 | |
# we multiply the recursively calculated $v0 with $a0 | |
# (which is now n since we popped it from the stack) | |
# and we store the result back into $v0 | |
mul $v0, $v0, $a0 | |
# we return from the procedure | |
jr $ra | |
fact_early_return: | |
addi $v0, $zero, 1 | |
jr $ra | |
exit: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment