C++ Program to Print Fibonacci Series

C++ program to print fibonacci series is provided on this page.

The aim of this program is to generate and print fibonacci series upto a given number.

Fibonacci Series is a sequence of numbers such that each number is sum of two preceding numbers.

The fibonacci series starts with 0 and 1 as first two numbers.

Since we are going to write a c++ program for fibonacci series we will need a formula.

Formula to find nth term in fibonacci series:
F[n] = F[n-1] + F[n-2]

C++ program to print fibonacci series

Here is the c++ program to generate and print the fibonacci series using above formula.

/* Fibonacci series upto given number in C++ */

#include<iostream>
using namespace std;
 
int main()
{
    int an0 = 0, an1 = 1, an2 = 1, given_number = 1000;
 
    cout << "Fibonacci Series:" << endl;
    cout << an1 <<" " << an1 << " ";

    while (an0 + an1 < given_number)
    {
        an2 = an0 + an1;
        an0 = an1;
        an1 = an2;
        cout << an2 << " ";
    }
    cout << endl;
    return 0;
}

Output:

Fibonacci Series: 
1 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 

Comments