Printing Fibonacci sequence using recursion in mips

3.4k Views Asked by At

Hey guys I need to print out the values of the Fibonacci sequence up till the nth value (user inputted). So if the user entered 3, I would have to print 1, 1, 2. I have to do it recursively and iteratively. I got the iterative part but I am having a little trouble with the recursive part. In the program I can get it to print the values. Any help would be appreciated.

.data

inputMsg: .asciiz "Enter number: "
iterationMsg: .asciiz "\nIterative: "
recursionMsg: .asciiz "\nRecursive: "
series: .asciiz "\nThe series is: "
space: .asciiz " "

.text

main:
    la $a0, inputMsg        #Print out inputMsg
    li $v0, 4
    syscall

    li $v0, 5           #Read in integer into v0
    syscall

    subi $s0, $v0, 1        #s0 = v0-1
    add $s7, $s0, 0         #s7 = s0
    add $s3, $v0, 0     #s3 = v0-1

    addi $s1, $s1, 1        #s1 = 1
    addi $s2, $s2, 1        #s2 = 1

    la $a0, iterationMsg        #Print out text_iteration
    li $v0, 4
    syscall

    la $a0, series          #Print out series
    syscall

    addi $a0, $zero, 1      #a0 = 1
    li $v0, 1
    syscall             #Prints out 1

    jal iterative           #Jump to iterative

    la $a0, recursionMsg        #Print Out Recursion text
    li $v0, 4
    syscall

    la $a0, series          #Print out Series text
    syscall

    add $a0, $s3, $0        #t0 = s3 = inputted val
    add $s0, $0, $0
    jal recursive

exit:       
    li, $v0, 10         #Exit Program
    syscall

iterative:
    beq $s0, 0, iterativeExit   #if s0 = 0 then exit
    subi $s0, $s0, 1        # s0 = s0 

    add $t0, $s2, $zero     # t0 = s2(1) + 0 
    add $s2, $s1, $s2       # s2 = s1(1) + s2(1)
    add $s1, $t0, $zero     # s1 = t0(1) + 0

    la $a0, space
    li $v0, 4
    syscall

    add $a0, $s1, $zero
    li $v0, 1
    syscall

    bnez $s0, iterative

iterativeExit:
    jr $ra

recursive:
    addi $sp, $sp, -4   #create/save stack

    sw $ra, 0($sp)

    sub $a0, $a0, 1     #minus one from inputted val (a0) till 0
    beq $a0, 1, oneRec
    jal recursive

    jal print

        lw  $ra, 0($sp)         #
        addi $sp, $sp, 4      # decrease the stack size

    jr $ra
oneRec:
    li $a0, 1
    li $v0, 1
    syscall

    addi $s0, $a0, 0

    la $a0, space
    li $v0, 4
    syscall

    jr $ra
print:
    add $t0, $0, $a0
    add $a0, $s0, $a0

    li $v0, 1
    syscall

    la $a0, space
    li $v0, 4
    syscall

    add $s0, $t0, $0
    jr $ra
1

There are 1 best solutions below

0
On

There is a small error up top. you have $s3 = what you say is $v0 - 1 but you actually have it = to $v0. And you use $s3 in your recursive part