The recursive definition of the fibonacci function is
fib(n) = fib(n-1) + fib(n-2)
so just change
int sum = fibonacci(n - 1) + fibonacci(n - 1);
to
int sum = fibonacci(n - 1) + fibonacci(n - 2);
Testing:
Please input the Limit: 5
1 0 1 1 2 1 0 1 3 1 0 1 1 2 5
Please input the Limit: 6
1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 1 0 1 1 2 1 0 1 3 8
EDIT 1
You would like to print the fibonacci sequence fib(0), fib(1), ... with this algorithm. If you beef up your output a little you'll see how this works for fib(5):
fib 1 = 1
fib 0 = 0
fib 2 = 1
fib 1 = 1
fib 3 = 2
fib 1 = 1
fib 0 = 0
fib 2 = 1
fib 4 = 3
fib 1 = 1
fib 0 = 0
fib 2 = 1
fib 1 = 1
fib 3 = 2
fib 5 = 5
5
As you see quite a few values are computed several times, which explains the sequence that is printed. One way to compute each result only once is Memoization. If you use memoization and only print the first time a result is determined you'll get:
fib 1 = 1
fib 0 = 0
fib 2 = 1
fib 3 = 2
fib 4 = 3
fib 5 = 5
5
so even then you don't get the order you want. So you'd have to use memoisation and only print the hash map at the end of the process.
5
fib 0 = 0
fib 1 = 1
fib 2 = 1
fib 3 = 2
fib 4 = 3
fib 5 = 5
Of course, you could also just create an additional loop and print all values for fib(i) for i from 1 to n. That would be fairly inefficient though.
EDIT 2
Disclaimer: I have no clue about C++. I wrote my last C program ages ago. But the following works, other people will do it better I'm sure.
So here's a simple example of memoization using a plain array, no hash map. Since you didn't say which concepts you have learnt until now I hope this is simple enough.
#include <iostream>
#define MAX 100
#define UNDEF -1
using namespace std;
int memo[MAX]; // memoization of results
int fibonacci(int n) {
int res = memo[n];
if (res != UNDEF) return res; // result has been computed before
if (n == 0 || n == 1)
res = n;
else
res = fibonacci(n - 1) + fibonacci(n - 2);
memo[n] = res; // memoize result
return res;
}
int main() {
int n, i;
do {
cout << "Please input the Limit (max " << MAX << ") : ";
cin >> n;
} while (n < 0 || n >= MAX);
for (i=0; i<=n; i++) memo[i] = UNDEF; // intitialize memo
fibonacci(n);
for (i=0; i<=n; i++) cout << memo[i] << " "; // print results
cout << endl;
}
Testing:
Please input the Limit (max 100) : 40
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155
.netnorvisual-studiorelated in this questionvoid main()is not standard C++, might be a visual studio extension. Hardly merits the tag though.n-2?int sum = fibonacci(n - 1) + fibonacci(n - 2)