I’m just beginning to learn recursion and I’m stuck on a problem which involves finding the number of cannonballs in a pile of cannonballs with each level obviously being a square number eg. the top stack is 1, the second is 4, the third is 16 and so on…

I’ve traced the steps in Xcode watching the variable’s values and what I’m seeing is that when the base case is reached the ‘numBalls’ is correct but when the stack frames end, the value is not returned and is lost.
I feel like I should know how to fix this, but I can’t seem to figure it out.
Here is the code I’m using:
#include <iostream>
using namespace std;
int GetCannonballs(int height, int numBalls);
int Cannonballs(int height);
int main(int argc, char *argv[]) {
cout << Cannonballs(3) << endl;
}
int GetCannonballs(int height, int numBalls)
{
if(height <= 0) {
return numBalls;
} else {
return GetCannonballs(height-1, numBalls + (height*height));
}
}
int Cannonballs(int height) // Wrapper function
{
int numBalls = 0;
GetCannonballs(height, 0);
return numBalls;
}
The return value I get is 0.
Any help or explanation of my error or misunderstanding would be very appreciated!
Thank you.
In
You forget to set
numBallsto the result ofGetCannonballs. You need to doOr more succinctly,
Note that you can get rid of the wrapper function by using default arguments for
GetCannonballs:Congratulations on writing a proper tail-recursive function by the way.