C++ Program to Print Fibonacci Series

The Fibonacci sequence is a series where the next term is the sum of pervious two terms. The first two terms of the Fibonacci sequence is 0 followed by 1.

// Example
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8

How to execute this Program.

  • Define Variables “num”, “first”, “second”, next. ( Where first=0 & second=1 )
int num, first=0, second=1, next;
  • Take the number of terms as input from User and save it in the variable “num”.
cout<<"Enter the number of terms:";
    cin>>num;
  • Print the Fibonacci Series using for() Loop
for(int i=0; i<num;i++)
    {
        cout<<first<<" ";
        next = first+second;
        first = second;
        second = next;
    }

Code : To Print Fibonacci Series

#include <iostream>
using namespace std;
int main ()
{
    int num, first=0, second=1, next;
    cout<<"Enter the number of terms:";
    cin>>num;

    cout<<"Fibonacci Series: ";

    for(int i=0; i<num;i++)
    {
        cout<<first<<" ";
        next = first+second;
        first = second;
        second = next;
    }

    return 0;
}

Output

Logic

 for(int i=0; i<num;i++)
    {
        cout<<first<<" ";
        next = first+second;
        first = second;
        second = next;
    }

Leave a Reply