Greetings. I'm just starting programming in C and I'm stuck on the logic of a simple recursive function. I'm working with a function that calculates the value of 3 raised to the nth power. My solution was:
Code:
int result = 3;
long power(int exponent)
{
if(exponent<1)
return 1;
else
result *= 3;
power(exponent-1);
return result;
}
This worked fine. However, according to the book that I'm learning from, the solution is written more compactly as:
Code:
long power(int exponent)
{
if(exponent<1)
return 1;
else
return (3 * power(exponent-1));
}
I don't understand how the two are equivalent. In other words, how exactly does "(3 * power(exponent-1))" work? It seems to me that "power(exponent-1)" must evaluate to the product of 3 multiplied by itself (exponent-1) times, but how is this calculation accomplished? Where does the 3*3*3... actually happen?
Thanks for your help!