Skip to content

Instantly share code, notes, and snippets.

@quinnzipse
Last active April 8, 2020 19:23
Show Gist options
  • Save quinnzipse/b1993484967ca9886f03ff370a838a2c to your computer and use it in GitHub Desktop.
Save quinnzipse/b1993484967ca9886f03ff370a838a2c to your computer and use it in GitHub Desktop.
.data
prompt1: .asciiz "Please enter a positive number: "
incorrectPrompt: .asciiz "Invalid number, please try again.\n"
prompt2: .asciiz "The "
prompt3: .asciiz " fib number is: "
newLine: .asciiz "\n"
.text
la $a0, prompt1
la $a1, incorrectPrompt
jal readNonNegInt
move $a0, $v0
move $s0, $v0
jal fib
move $s1, $v0
la $a0, prompt2
move $a1, $s0
jal printInt
la $a0, prompt3
move $a1, $s1
jal printInt
j exit
fib:
bgt $a0, 1, rec #if it is 1 or 0 it is just that number for the fib #
move $v0, $a0
jr $ra
rec:
addi $sp, $sp, -12
sw $ra, 0($sp) #put the return address on the stack
sw $a0, 4($sp) #put the value of $a0 on the stack
addi $a0, $a0, -1
jal fib
sw $v0, 8($sp) #put the result of the first recursive method on the stack
addi $a0, $a0, -1
jal fib
lw $t0, 8($sp) #restore the result for the first recursive method
add $v0, $t0, $v0 #add them together
#restore from the stack
lw $ra, 0($sp)
lw $a0, 4($sp)
addi $sp, $sp, 12 #update stack pointer
jr $ra #return :)
exit: li $v0, 10
syscall
readInt: li $v0, 4
syscall
li $v0, 5 # Set to read an int
syscall
jr $ra # return
readNonNegInt: add $s0, $ra, $zero
jal readInt # call readInt
move $ra, $s0
bltz $v0, incorrect # if it is a negative number reprompt
jr $ra # return
incorrect: move $t0, $a0 # Save the $a0 var for calling readNonNegInt
move $a0, $a1 # prep to write the incorrect prompt
li $v0, 4 # prep to write a string
syscall
move $a1, $a0
move $a0, $t0
j readNonNegInt
printInt: li $v0, 4 # prep the syscall for a print string
syscall
move $a0, $a1 # load the int we are trying to print
li $v0, 1 # get ready to print it.
syscall
jr $ra #return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment