Can someone explain to me how the variables base and powerRaised are being passed through calculatePower so I can have a better understanding of recursion and maybe understand how to write my own recursive functions thanks.
the same way they are passed when you initially called calculatePower. Think of it like this:
1 2 3 4 5 6 7 8
int calculatePower(int base, int powerRaised)
{
if (powerRaised != 1) {
int result = calculatePower(base, powerRaised - 1);
return base * result;
} elsereturn 1;
}
As you can see, it is still just a normal function call, with the same values (except powerRaised is now one less than before).
I don't understand your question about "how the variables are passed". In the normal way, like any other function.
The function calls pile up on the stack. So if you call it with 2 and 5 (2 to the power of 5):
b p
2 5 first call (from main)
2 4 first recursive call
2 3 next call
2 2 ...
2 1 ...
2 0 finally hit the base case (p == 0)
The last call (2, 0) finally hits the base case which returns the value 1.
That value is multiplied by b and returned, so it returns 2.
That value is multiplied by b and returned, so it returns 4.
Then 8.
Then 16.
Then finally 32, which is 2 to the 5th power.
b p
2 5 -> 32 ^ 32 is returned to the initial call from main
2 4 -> 16 ^
2 3 -> 8 ^
2 2 -> 4 ^
2 1 -> 2 ^
2 0 -> 1 ^ the returns pop back up the stack
@AL88 to write your own recursive function, structure as follows (pseudo-code):
MyRecursive(params)
{
if "Base Case" conditions met
return
Do stuff with params
MyRecursive(progression on the params)
}
1. Design the base case first, or the situation in which the recursion will end. There may be more than one. Return.
2. Next, do something with the parameters. Sometimes you may want to do something briefly before the base cases, but usually after.
3. Lastly, think about how to progress to the next piece.
#include <iostream>
usingnamespace std;
void DownToZero(unsigned n)
{
// Stuff, usually after base cases. Here I wanted to print out the zero
cout << n << "... ";
if (n==0) // Base Case
{
cout << "BOOM!\n";
return;
}
DownToZero(n-1); // Recursive call with progression, subtracting 1
}
int main()
{
DownToZero(3);
return 0;
}