This class we were oredered to write a code that generates the Fibonacci series. I was a really challenging task, ’cause my logic didn’t adapted to the situation righly.
Finally I used some loops, vectors and a function to make it work. This is what I wrote.
#include <iostream> using namespace std; int fibonacci(int n) { int sum[n]; sum [0]=0; sum [1]=1; for(int c=2 ; c<=n ; c++) { sum[c]=sum[c-1]+sum[c-2]; } return sum[n]; } int main() { int n; cout << "Introduce the last number position of the series: "; cin >> n; int sum[n]; for(int c=0 ; c<=n ; c++) { sum[c] = fibonacci(c); } for(int c=0 ; c<=n ; c++) { if (sum[c]==sum[n]) cout << sum[c]; else cout << sum[c] << ", "; } cout << endl; return 0; }
Actually, this code is not so complicated to do, you just need to see it in a different way, thinking how to explain to a computer that it is required to sum the two numbers before to obatain the third value.
Now, I have to change loops for recursions, but since I need to do other things, I will let it for the weekend. Meanwhile, do you want to try it?