Printing Fibonacci Series in C++

Exercise

Write a C++ program to print Fibonacci series on the display screen.

Method 1: Fibonacci series of entered number of terms.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    int num, n1 = 0, n2 = 1, sum = 0;
    cout << "Enter the number of terms to be displayed: ";
    cin >> num;
    cout << "Fibonacci Series: ";
    for (int i = 1; i <= num; ++i)
    {
        // first two terms are displayed.
        if(i == 1)
        {
            cout << " " << n1;
            continue;
        }
        if(i == 2)
        {
            cout << " "<< n2;
            continue;
        }
        sum = n1 + n2;
        n1 = n2;
        n2 = sum;
        cout << sum << " ";
    }     
    return 0;
}
Click Here to View the Output:
Enter the number of terms to be displayed: 13
 Fibonacci Series:  0 1 1 2 3 5 8 13 21 34 55 89 144
Click Here to View the Explanation:

The previous two terms are added to give the Fibonacci sequence. The beginning two terms for the Fibonacci sequence are 0 and 1, respectively.

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
  • The program uses if statements within for loops.
  • The loops work for the first assigned numbers: n1 = 0 and n2 = 1.
  • They pass through if statement and the first two numbers are printed on the screen. n1 and n2 are summed and saved as the third term: sum
  • n1 and n2 and assigned new values: n2 and sum, respectively.

Method 2: Fibonacci Series up till the entered number:

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    int num, n1 = 0, n2 = 1, sum = 0;
    cout << "Enter a number for the final range of series: ";
    cin >> num;
    // displays the first two terms which is always 0 and 1
    cout << "Fibonacci Series: " << n1 << ", " << n2 << ", ";
    sum = n1 + n2;
    while(sum <= num)
    {
        cout << sum << ", ";
        n1 = n2;
        n2 = sum;
        sum = n1 + n2;
    }
    return 0;
}
Click Here to View the Output:
Enter a number for the final range of series: 65
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
Click Here to View the Explanation:
  • User is requested to enter num how many numbers from Fibonacci series they want printed.
  • This code uses for loops. The terms are added, and assigned new terms like the previous method.
  • The assigned terms n1 and n2 are added.
  • If sum is less than the number given by the user num, it is displayed. And when the number exceeds num, the loop is exited.
  • The output is printed on the screen.

%d bloggers like this: