Files
cs2810/Fibonacci.asm
2026-08-04 06:59:21 -06:00

54 lines
1.7 KiB
NASM

.data
welcomeMessage: .asciiz "Welcome to a MIPS assembly Fibonacci Sequence calculator!\nThis will calculate the nth term of the Fibonacci Sequence.\n"
prompt: .asciiz "Enter a number (n, input n > 2) to find the nth term:"
foundTerm: .asciiz "The nth term is: "
.text
main:
li $v0, 4 # syscall 4 is to print a string
la $a0, welcomeMessage # store the ascii string in register a0
syscall # print
jal getInput # get the user input
jal fibonacci # calculate the nth fibonacci term
move $a0, $v0 # move the returned term to register a0
li $v0, 1 # syscall 1 is to print an int
syscall # print
ori $v0, $0, 10 # system call code 10 for exit
syscall # exit the program
getInput:
li $v0, 4 # syscall 4 is to print a string
la $a0, prompt # store the ascii string in register a0
syscall # print
li $v0, 5 # syscall 5 is for reading an int
syscall # read an int from the user
move $a0, $v0 # load input into register a0
jr $ra # return to caller
fibonacci:
move $s1, $a0 # Copy the nth term
li $t0, 2 # Counter
li $t1, 0 # Prev value
li $t2, 1 # Current value
li $t3, 0 # Next value
while:
bge $t0, $s1, done # While the counter is less than n
add $t3, $t1, $t2 # Sum the previous and current values and save in register t3
move $t1, $t2 # Shift current value to previous value
move $t2, $t3 # Shift next value to current value
addi $t0, $t0, 1 # Increment counter
b while # Jump back to start of while loop
done:
move $v0, $t2 # Move current value to register v0
jr $ra # Return to caller