To give you a small hint without doing all the work for you (as this seems to be some task for school, college, or university), here’s how a Fibonacci number is defined:
f(0) = 0;
f(1) = 1;
f(n) = f(n - 1) + f(n - 2);
So in C++ this could be written like this:
int fibonacci(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
This of course can be further optimized and it’s not necessarily the best approach. And it also includes possible errors, that might lead to stack overflows (hey, isn’t that what this site is about? :)). So try to understand the code, then try to learn and improve it. Don’t just copy & paste.
1
solved Calculating Fibonacci Numbers [closed]