0
function power(base, exponent) {
  if (exponent == 0)
    return 1;
  else
    return base * power(base, exponent - 1);
}

If I change it to return 2, it doubles the answer, 3 triples etc.

I understand what it's doing, but I haven't learned how it knows to produce a multiple of the return from the 'else' part. Please explain.

EDIT: While I'm here, how is the else working? I would assume base is being multiplied by base, and then the exponent is subtracting from itself, but when I do something like: base * (2, 5-1) it multiplies base by 4... I must be missing something simple.

Martin
  • 171
  • 1
  • 8

3 Answers3

2

If you return 1, then calling power(7, 3) will result in:

7 * 7 * 7 * 1

If you return 2, then it will result in:

7 * 7 * 7 * 2

where the last number is the number that you are returning.

Do you now see why changing the return value doubles the result?

To answer your second question, this due to the behavior of the comma operator, which evaluates to the value of the expression after the last comma so:

base * (2, 5 - 1)
base * (5 - 1)
base * (4)

This is completely unrelated to calling a function with the parameters 2 and 5 - 1.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

It doesn’t have to "know" anything. It keeps recurring until the exponent is zero.

how is the else working?

If exponent != 0 it runs, its the opposite of the if.

InternalFX
  • 1,475
  • 12
  • 14
0

This is a recursive function that calls itself over and over until it finds the correct answer. Tracing the way the function works should help you understand it.

Take power(2, 5) for example.

power(2, 5) = 2 * power(2, 4)
            = 2 * 2 * power(2, 3)
            = 2 * 2 * 2 * power(2, 2)
            = 2 * 2 * 2 * 2 * power(2, 1)
            = 2 * 2 * 2 * 2 * 2 * power(2, 0)
            = 2 * 2 * 2 * 2 * 2 * 1

All together, you end up with 2 * 2 * 2 * 2 * 2 * 1 which is 25, as expected. The else in your function gets triggered when the exponent parameter (the 5 in the example) is greater than zero. Since 5 is greater than 0, the else part is triggered and the function is called again with 4 as the exponent. Since 4 is greater than 0, the else part is triggered and the function is called again with 3 as the exponent. The same thing happens with 2, then 1, then 0. When power(2, 0) is finally called, the function just returns 1.

Luke Godfrey
  • 67
  • 1
  • 6