Let's say we write a simple recursive function fib(n)that calculates the nth Fibonacci number. Now we want the function to print this nth number. Since the same function is called repeatedly, there must be a condition that allows only the root call to be printed. The question arises: how to write this condition without passing any additional arguments or using global / static variables.
So we are dealing with something like this:
int fib(int n) {
if(n <= 0) return 0;
int fn = 1;
if(n > 2) fn = fib(n-2) + fib(n-1);
if(???) cout << fn << endl;
return fn;
}
int main() {
fib(5);
return 0;
}
I thought that the root call is different from all the children, returning to another caller, namely the main method in this example. I wanted to know if this property can be used to record a condition and how.
: , , . . . .