Write a C++ Program to Display Fibonacci Series

Fibonacci series is a sequence of numbers in which each number is the sum of the previous two numbers.

The series is named after the Italian mathematician Leonardo of Pisa, who is also known as Fibonacci.

The first two numbers of the series are 0 and 1. The rest of the numbers are obtained by adding the previous two numbers.

The Fibonacci series starts with 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on.

In this tutorial, we will show you how to write a C++ program to display the Fibonacci series up to a given limit.

The program will prompt the user to enter the limit, and then it will display the Fibonacci series up to that limit.

Here is the C++ program to display the Fibonacci series:

#include <iostream>
using namespace std;

int main() {
   int n, t1 = 0, t2 = 1, nextTerm = 0;

   cout << "Enter the number of terms: ";
   cin >> n;

   cout << "Fibonacci Series: ";

   for (int i = 1; i <= n; ++i) {
      if(i == 1) {
         cout << t1 << ", ";
         continue;
      }
      if(i == 2) {
         cout << t2 << ", ";
         continue;
      }
      nextTerm = t1 + t2;
      t1 = t2;
      t2 = nextTerm;
      
      cout << nextTerm << ", ";
   }
   return 0;
}

Let’s break down the program step by step:

The first three variables declared are n, t1, and t2. n is the number of terms to be displayed, and t1 and t2 are the first two terms of the series. We set t1 to 0 and t2 to 1 as these are the first two terms of the series.

We then prompt the user to enter the number of terms they want to display using cout and cin statements.

Next, we start a for loop that will iterate from 1 to n. Inside the loop, we check if the current iteration is the first or second term of the series.

If it is, we simply display the value of the corresponding variable using cout statements and the continue statement to skip to the next iteration of the loop.

If it is not the first or second term, we calculate the next term of the series using the formula nextTerm = t1 + t2 and then update t1 and t2 to prepare for the next iteration of the loop.

Finally, we display the next term of the series using cout statements.

That’s it! With this simple program, you can easily display the Fibonacci series in C++.