OneCompiler

C++ program to print Fibonacci series

308

Consider you want to print the Fibonacci series upto terms given by user.

Fibonacci series starts from 0 and 1 and then continued by the addition of the preceding two numbers. For example : 0, 1, 1, 2, 3, 5, 8, 13,....

#include <iostream>
using namespace std;

int main() 
{
  int first = 0;
  int second = 1;
  int i, next, terms;
  
  cout << "Enter how many terms:";
  cin >> terms;
  
  if (terms <= 0){
     cout << "Invalid input";
  } else if (terms == 1){
      cout << "\nFibonacci series up to ",terms," terms:";
      cout << first;
    } else {
      cout << "\nFibonacci series up to ",terms," terms:";
        for ( i=0;i<terms;i++){
          cout << endl << first;
          next = first + second;
          first = second;
          second = next;
        }
      }
  return 0;
}

Try yourself here by providing input in the stdin section.

In the above program,

  • Initializing first to 0 and second to 1.
  • we are checking if the input given by user is valid.
  • If the user requested for only 1 term then print 0.
  • Otherwise we are using for loop based on the condition, count(i) should be less than terms given by user.
  • Logic:
     next = first + second
     first = second
     second = next

Results

Enter how many terms: 10
Fibonacci series up to 10 terms:
0
1
1
2
3
5
8
13
21
34