this is easy to do in a for loop, however hard for a recursive program
Sorry, you are wrong -- it is trivial to add counters or such for a recursive program in C++.
a) Note that no global is needed.
b) No extra method parameter is needed.
As usual, the C++ solution is to create a class
The non-static recursion method as part of a class will always have the this pointer, and thus access to any part of the class, including any number of added counters and reports or methods you might need.
Here is one possible approach:
class FibRec
{
public:
FibRec() : counter(0) {
std::cout << "FibRec ctor " << counter << std::endl;
};
~FibRec() { // output final value with dtor
std::cout << "FibRec dtor " << counter << std::endl;
};
int exec( int x )
{
if (x == 0) return 0;
else if (x == 1) return 1;
else
{
counter++;
// dbg: std::cout << counter << " " << x << std::endl;
return (exec(x - 1) + exec(x - 2));
// note -- Fibonacci fix?
}
}
private:
int counter;
};
int t407(void)
{
FibRec f; // class instance
f.exec(5); // invoke recursive method
return(0);
}
Note: The default stack size on ubuntu 15.10, using g++, is 8 Mbytes. That is a LOT of recursion.
Unfortunately, your code has a mistake - it 'adds' and grows to overflow very quickly. My code shows overflow when counter is 272,261. You'll need to fix the code.
I'm guessing that this code is supposed to be fibonacci, which is the sum of two intermediate values. Not what you have coded.
You might achive what you want by changing your code from:
return fibRec((x - 1) + (x - 2), counter);
to:
return (fibRec(x - 1, counter) + fibRec(x - 2, counter));
Good luck.