OK, recursion is one of those things that can easily confuse:-)
If you call exponent(2,1) it will see power ==1 and return 2 - simple.
A call to exponent(2,2) will have power >2, so will return 2*exponent(2,(2-1)), so the function exponent calls itself (this is recusion) and calculates exponent(2,1) = 2. The first instance of exponent then returns 2*2 = 4.
As you increse the value of power, the number if times exponent is called increases.
One thing you could do, which might help see what it is doing, is to change exponent as follows to see the sequence of calls.
1 2 3 4 5 6 7 8 9 10 11
|
ulong exponent(ushort number,ushort power)
{
ulong result;
cout << "Enter Power : " << power << endl;
if (power==1)
result = number;
else
result = (number*exponent(number,power-1));
cout << "Exit Power : " << power << endl;
return result;
}
|
By using a local varaible for the result you can put a cout after the recusion, and should see something like
Enter 3
Enter 2
Enter 1
Exit 1
Exit 2
Exit 3
Note: Recusion is a way to code some problems very 'neatly', but can eat up memory very quickly if you are not careful.
In the modified version of exponent, for example, it has to hold a ulong for each 'level' of recusion - so if power = 3, it needs to store 3 ulongs when calculating the result. If power = 100, that's 100 ulongs.
If the recusive function is more complex, requires more local variables, etc, you can eat memory very quickly!