The answer is pretty simple. And can be done can be done with a few tweaks in your code
Your first for
loop will produce an out of bounds error as in the 9th iteration (i = 8) you will be accessing a non existent arr[10].
Here is the corrected code:
#include <iostream>
using namespace std;
int main () {
cout <<"Fibonacci series " << endl;
int arr[10];
arr[0] = arr [1] = 1;
for (int i = 2; i < 10; i++){
arr[i] = arr[i-1]+arr[i-2];
}
for (int i = 0; i < 10; i++)
cout << arr[i] << endl;
return 0;
}
In the above code you can replace 10 with any other number and it will produce that many numbers in the series. Replace the 10 in array declaration, and both the for loop end condition.
You can also do this without an array and only one loop if you just need to print the series:
#include <iostream>
using namespace std;
int main () {
cout <<"Fibonacci series " << endl;
int a = 1, b = 1;
cout << a << endl << b << endl;
for (int i = 0; i < 10; i++)
{
((a<b) ? a : b ) = a + b;
cout << ((a>b) ? a : b ) << endl;
}
return 0;
}
In the for
loop the smallest of the two number is selected and is assigned the sum of the two no’s. Then the largest of the two is printed which is the number which was just modified.
eg:
Output initial : 1 1
1: i = 2; a = 1; b = 1; the smallest of the two (here b as a < b
fails) is assigned the sum of the two values which is the next number in the series, b = 2. Now the larger number (which is the number just modified as a+b > b
) is printed. output : 1 1 2
2: i =3; a = 1; b = 2; the smaller (now a) is assigned the sum (3), a = 3;Now the larger number (which is the number just modified as a+b > b
) is printed. output : 1 1 2 3
and so on
EDIT: For your comment to take n
as user input, you better use std::vector or a pointer. Really recommend the former as it is a lot less mess and less prone to help in “shooting yourself in the foot”.
The code will look like :
#include <iostream>
#include <vector>
using namespace std;
int main () {
cout <<"Fibonacci series " << endl;
vector<int> arr;
int n = 0;
cout << "Enter no to print \n";
cin >> n;
arr.push_back(1);
arr.push_back(1);
for (int i = 2; i < n; i++){
arr.push_back(arr[i-1]+arr[i-2]);
}
for (int i = 0; i < n; i++)
cout << arr[i] << endl;
return 0;
}
And with pointers :
#include <iostream>
using namespace std;
int main () {
cout <<"Fibonacci series " << endl;
int* arr;
int n = 0;
cout << "Enter no to print \n";
cin >> n;
arr = new int [n];
arr[0] = arr [1] = 1;
for (int i = 2; i < n; i++){
arr[i] = arr[i-1]+arr[i-2];
}
for (int i = 0; i < n; i++)
cout << arr[i] << endl;
delete[] arr;
return 0;
}
EDIT Thanks @Xam
8
solved How to generate 10 terms of Fibonacci series in c++? [duplicate]