I have this example block of code that I tried to replicate, a recursive function for finding Fibonacci numbers
#include <iostream>
using namespace std;
int fibonacci(int n)
{
if (n==0)
return 0;
else if (n==1)
return 1;
else return fibonacci(n-1)+(n-2);
}
int main()
{
cout<<fibonacci(15);
}
the following example outputs
92
when executed.
Looking at some examples now, I see that the formula is wrong, but I am still curious as to why the output is what it is, as I have been having a hard time trying to understand how recursion works.
cout<<nat the beginning of yourfibonacci()function.fibonacci(n-1)+(n-2);is equivalent tofibonacci(n-1) + n - 2;So, it's basically equal to15 + 14 + 13 + 12 + 11 + 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 - 2 * 14, or in more general terms:sum (n) - 2 * (n - 1)What's unclear about that?