1

I wrote a simple code for a recursive function that does something like the following in C:

Int function1(int n)
{
    if (n <= 3)
     {
        int ans1 = (3*n)-5;
        return ans1;
    }
    else
     {
        int ans1 = (n-1)*function1(n-1) + function1(n-2) - n;
        return ans1;
     }
}

And the main calls the function.

Apparently, it's not returning an expected answer. when the input is '8', the expected output is '7842'. What's wrong with my code?

Assume that I have all the string variables for output declared

 main:  
        la      $a0, msg1
        li      $v0, 4
        syscall

        li      $v0, 5
        syscall
        move    $a1, $v0

        la      $a0, msg2
        li      $v0, 4
        syscall

        addi    $sp, $sp, -4
        sw      $ra, 0($sp)
        jal     Function1
        lw      $ra, 0($sp)
        addi    $sp, $sp, 4


        move    $a0, $v0
        li      $v0, 1
        syscall

        la      $a0, space
        li      $v0, 4
        syscall

        jr      $ra


 Function1:
        addi    $sp, $sp, -4
        sw      $ra, 0($sp)
        addi    $sp, $sp, -4
        sw      $s0, 0($sp)

        move    $s0, $a1
        li      $t0, 3
        ble     $s0, $t0, Done

        addi    $a1, $s0, -1

        jal     Function1

        mult    $a1, $v0
        mflo    $t1

        addi    $a1, $s0, -2

        jal     Function1


        add     $t2, $t1, $v0
        sub     $v0, $t2, $s0

 Done:
        li      $t0, 3
        mult    $t0, $a1
        mflo    $t1
        addi    $v0, $t1, -5

        lw      $s0, 0($sp)
        addi    $sp, $sp, 4
        lw      $ra, 0($sp)
        addi    $sp, $sp, 4

        jr      $ra
Jason Kwon
  • 11
  • 1
  • 1
    What *does* it output? Maybe this a [mcve] by including that, and what you find when single-stepping with your debugger. – Peter Cordes Sep 20 '18 at 08:40
  • Same C as [Stuck on a MIPS recursive function](https://stackoverflow.com/q/52349742), I knew this looked familiar. But unfortunately that question doesn't have a useful answer for this: the OP there got the expected value of the C wrong. But their MIPS code does use the newer `mul $v0, $v0, $a0` instruction instead of `mult`, avoiding the mflo. And BTW, `n*3` is `n*2 + n`, or `n+n+n` (Two add instructions or `sll`+`add` are much faster and easier to write than `mul`) – Peter Cordes Sep 20 '18 at 08:53
  • The main takes the input of the user and outputs the result of the function(input). in case input is 8, the expected output is 7842. – Jason Kwon Sep 20 '18 at 09:28

0 Answers0