#include <iostream>
usingnamespace std;
/*int getFibNumber(int fibIndex){ // works fine
if (fibIndex < 2)
return fibIndex;
else
return getFibNumber(fibIndex - 1) + getFibNumber(fibIndex - 2);
}*/
int main()
{
int index = 0;
cout << "Enter the desired number: ";
cin >> index;
index = (index - 1) + (index - 2); // does not work
cout << "Fibonacci number is: " << index << endl;
return 0;
}
getFibNumber is a recursive function. If you call it with 4, f(4), that function will call f(3) and f(2), which in turn call f(2), f(1), f(1), f(0), and first of those calls f(1) and f(0). That is 9 function calls.
The simple equation:
index = index - 1 + index - 2
Set index=4 =>
index = 4-1 + 4-2
= 3 + 2
= 5
There is nothing recursive in that.
The two functions are getFibNumber and the equation in the main. I'm trying to figure out what the difference between the two. Its confusing getFibNumber isn't a loop.
keskiverto just explained to you that getFibonacci is a recursive function. It calls itself from within the block, so it is essentially a loop.
getFibonacci calls itself, passing lower values of fibIndex until fibIndex is less than 2.
The real difference between the two methods you show is that getFibonacci can calculate as many iterations as needed while main will not be able to calculate the correct Fibonacci numbers that require more than 3 iterations. In addition, there is no check if index is less than 2, so if the user puts in 1, a negative number is returned.
I was talking about his main function. I guess I could have made that more clear.
1 2 3 4
cin >> index; //user puts in 1
//No check if index < 2 as in getFibonacci
index = (index-1) + (index-2); // index = 0 + -1
cout << "Fibonacci number is: " << index << endl; // "Fibonacci number is: -1