phprecursion

How does a recursive multiplication function work?


function f2($n, $a)
{
    if ($n == 0)
      return 0;
   return $a + f2($n-1, $a); // Changed return a... to return $a...
}

echo f2(3,4);

this outputs 12, I just don't understand why. Here's what I think, though:

obviously, $n and $a are the variables that will be take the place of the values. so like n is 3 and a is 4 in this example. the base case is the if statement, and it acts like a loop between the n. so since n is 3, and n is set to = 0 , then the code loops 3 times.

now i dont get the return a + f2(n-1, a) part. obviously that's where the math is calculated, but how?

it loops like this i think:

4 + f2(2, 4)
4 + f2(1, 4)
4 + f2(0, 4)

but what does it add to make the sum 12??

so what im asking is that if i understand it correctly and if not, what's actually happening and how is the output 12.


Solution

  • first call is f2(3,4)

    f2(3,4)
        |
      return 4 + f(2,4)
                    |
                 return 4 + f(1,4)
                              |
                            return 4 + f(0, 4)
                                           |
                                       return 0; // and now unwinding the stack, 0 gets passed to the prev. return called.
                                           |
                            return 4 +     0   // 4 gets passed to the prev. return called
                              |
                 return 4 + 4 + 0         // 8 gets passed to the prev. return called.
                    |
      return 4 + 4 + 4 + 0    // f2(3,4) now returns a value of 12
    

    looking at the call stack above , the first return called will be :

    return 4 + 4 + 4 + 0

    return a + call f2 , the + operator chains the a with the next function call, which at the end accumulates all your intermediate values in the first return called.