I'm having a tough time conceptualizing this problem. I have a recursive function computing the number of possible combinations of two numbers. I have it working fine, just need one thing sorted out. My output needs a counter to increment each recursive step. Like this:

Level 1:
...
Level 2
...
Level 3
...

The combinations are printing out correctly but I can't figure out how to increment the level correctly each time. Any help would be appreciated. Here's the code:

``````#include<iostream>

using namespace std;

long Combinations(int y,int x,int level)

{
if(x==1)
{
return y;
}
else if(x==y)
{
return 1;
}
else
{
cout << "Recursive Level " << level << endl;
cout << "y = " << y << "  x = " << x << endl;
return Combinations(y-1,x-1,level+1) + Combinations(y-1,x,level);

}
}

int main()
{

long result;
result = Combinations(8,4,1);
cout << result << endl;

return 0;
}``````
2
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by robotnixon

I'm not clear on what the problem is. Your code is reporting the depth of recursion on the variable x. Do you really want a count of how many recursive calls are made?

If so, create the counter variable in the function as static, increment at the entrance to the function, like:

``````int foo ( int x )
{
static int num_calls = 1;
cout << "call number: " << num_calls++ << endl;

//function continues``````

Okay I got it. Just needed to move the cout statements to the front of the function and use a static int. Which I had never used before (thanks vmanes). Tried something similar before but just kept getting 1's. And to clarify I did need to count every recursive call being made. Thanks again.