Fibonacci Series in C++
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 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:
where, and are the predefined value
Now, let us seed value into this formula. Considering n=2 we get
So, let us consider the following question to understand further.
Question:
Given a number n, print the 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++.
- Recursive Implementation
- 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.
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!