Fibonacci Series in C++

Video Tutorial
FREE
Fibonacci series thumbnail
This video belongs to
Data Structures in C++ Course
13 modules
Certificate
Topics Covered

Overview

Fibonacci series is a type of definite pattern that begins with 0,1 or 1,1.

Example of Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21 , 34 . . . . . .

The pattern in Fibonacci Series is generated by adding the previous two consecutive terms to form a number. For Example, the first term 0 and the second term 1 when added from the third number, which is 1. Whereas the second number 1 and third number 1 when added from the fourth number which is 2 and so on.

Fibonacci Series in CPP Example

Fibonacci Series in C++

Let us Consider the following Fibonacci Series.

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

In mathematical terms, the sequence Fn of a Fibonacci series is defined by a recursive relation.

Recursive Relation:

Fn=Fn1+Fn2Fn = Fn-1 + Fn-2

where, F(0)=0F(0) = 0 and F(1)=1F(1) = 1 are the predefined value

Now, let us seed value into this formula. Considering n=2 we get

f(2)=f(21)+f(22)>>f(2)=f(1)+f(0)>>f(2)=1+0>>f(2)=1f(2) = f(2-1) + f(2-2) -> -> f(2) = f(1) + f(0) -> -> f(2) = 1 + 0 -> -> f(2) = 1

So, let us consider the following question to understand further.

Question:

Given a number n, print the nthn^{th} Fibonacci Number as the output.

PseudoCode:

Output:

Ways to Write the Fibonacci Series Program in C++

There are two popular ways of implementing the Fibonacci series in C++.

  1. Recursive Implementation
  2. Iterative Implementation

Starting with Recursive implementation.

Code:

Output

Time Complexity: O(2^n)

Auxiliary Space Complexity: O(n) due to the recursion stack.

But all the calculation for the series was done under the hood.

Let us build a recursive tree to understand how the calculation is being done.

Fibonacci Series Recursive Tree

Next, we have Iterative Implementation.

Code:

Output:

Time Complexity: O(n), which is linear.

Space Complexity: O(1), which is constant.

Conclusion

We have discussed 2 popular methods to print the Nth Fibonacci number in C++. Now, it is totally up to you which method you find more suitable for the given problem statement.

If the space complexity does not matter then you can use the recursive approach, else you need to use the more efficient iterative approach.

Unlock the power of Dynamic Programming and take your coding skills to the next level – Enroll in Scaler Topics Dynamic Programming Course now!