Display Fibonacci Series using C++

03-11-17 Course- CPP

A series of number in which each number is the sum of preceding two numbers is known as Fibonacci series.


1, 1, 2, 3, 5, 8, 13, 21, 34...

Example 1: Fibonacci sequence up to nth term

In this example, user is asked to enter a positive integer (Suppose n) and Fibonacci series is displayed up to nth term


#include <iostream>
using namespace std;

int main() {
    int n, firstTerm = 1, secondTerm = 1, nextTerm;
    cout << "Enter number of terms: ";
    cin >> n;

    cout << "Fibonacci Series: " << firstTerm << " + " << secondTerm << " + ";
    for (int i = 1; i <= n-2; ++i) {
        nextTerm = firstTerm + secondTerm;
        cout << nextTerm << " + ";
        firstTerm = secondTerm;
        secondTerm = nextTerm;
    }
    return 0;
}

Output


Enter number of terms: 11
Fibonacci Series: 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 + 

Example 2: Fibonacci sequence less certain number entered by user.


#include <iostream>
using namespace std;

int main() {
    int n, firstTerm = 1, secondTerm = 1, nextTerm;
    cout << "Enter a number: ";
    cin >> n;

    cout << "Fibonacci Series: " << firstTerm << " + " << secondTerm << " + ";
    nextTerm = firstTerm + secondTerm;

    while ( nextTerm < n) {
        cout << nextTerm << " + ";
        nextTerm = firstTerm + secondTerm;
        firstTerm = secondTerm;
        secondTerm = nextTerm;
    }
    return 0;
}

Output


Enter a number: 38
Fibonacci Series: 1 + 1 + 2 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +