Possible Duplicate:
Using Recursion to raise a base to its exponent – C++
int raisingTo(int base, unsigned int exponent)
{
if (exponent == 0)
return 1;
else
return base * raisingTo(base, exponent - 1);
}
I wrote this code for raising an exponent to its base value using values passed by value from the main(). This function uses recursion to do this. Can someone explain how it returns a value each time it calls itself? I need a detailed explanation of this code.
It is best illustrated by doing iterations manually (as suggested in the comments). Suppose we have
base = 2andexponent = 2.2 * (whatever function yields when called with the arguments 2 and (2 - 1), which is 1).2 * (whatever the next iteration with arguments 2 and 0 returns).Now we have the full chain 2 * 2 * 1, therefore the result of the calculation is 4.