C++ Program to Display Fibonacci Series


The fibonacci series contains numbers in which each term is the sum of the previous two terms. This creates the following integer sequence −

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377…….

The recurrence relation that defines the fibonacci numbers is as follows −

F(n) = F(n-1) + F(n-2) F(0)=0 F(1)=1

Programs to Display Fibonacci Series

There are two methods to display fibonacci series i.e. using dynamic programming and recursive programming. These are further explained as follows −

Dynamic Programming

Example

#include<iostream>
using namespace std;
void fib(int n) {
   int f[n];
   int i;
   f[0] = 0;
   f[1] = 1;
   for (i = 2; i < n; i++) {
      f[i] = f[i-1] + f[i-2];
   }
   for (i = 0; i < n; i++) {
      cout<<f[i]<<" ";
   }
}
int main () {
   int n = 10;
   fib(n);
   getchar();
   return 0;
}

The output of the above program is as follows.

Output

0 1 1 2 3 5 8 13 21 34

In the program, main() is the driver function. The actual code for the creation of the fibonacci series is stored in the function fib() which is called from main.

An array f[n] is created which will store the first n terms of the fibonacci series. The first and second elements of this array are initialized to 0 and 1 respectively.

f[0] = 0;
f[1] = 1;

Then for loop is used to store each element in the array as the sum of its previous two elements.

for (i = 2; i < n; i++) {
   f[i] = f[i-1] + f[i-2];
}

Finally the fibonacci series is displayed.

for (i = 0; i < n; i++) {
   cout<<f[i]<<" ";
}

Recursive Programming

Let us see how to display fibonacci series using recursion.

Example

#include<iostream>
using namespace std;
int fib(int n) {
   if (n <= 1)
   return n;
   return fib(n-1) + fib(n-2);
}
int main () {
   int n = 10, i;
   for(i=0;i<n;i++)
   cout<<fib(i)<<" ";
   return 0;
}

Output

0 1 1 2 3 5 8 13 21 34

In the above program, a for loop is set that creates each term of the fibonacci series using recursion. This is done by calling the function fib() for each term in the series.

for(i=0;i<n;i++)
cout<<fib(i)<<" ";

The function fib() returns 0 or 1 if n is 0 or 1 respectively. If not, it calls itself recursively as the sum of the previous two terms until the correct value is returned.

if (n <= 1)
return n;
return fib(n-1) + fib(n-2);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements