Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Program to print upto nth terms 
2.1.
Using for loop
2.2.
Using while loop
3.
Recursion code for Fibonacci series
4.
Dynamic programming code for Fibonacci series
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Fibonacci series

Author Aditi
0 upvote

Introduction

The Fibonacci series is a series with a name based on an Italian scientist, and his name was Fibonacci. Series starts with zero(0) and one(1). Later series contains the sum of the previous two numbers in series. For example 0 1 1 2 3 5 8 …

Since the Fibonacci series contains two elements as 0 and 1 and then the sum of the previous two consecutive up to which the user wants. So printing can be accomplished by using loops. 

In this blog, we will learn different ways to print the Fibonacci series in the c++ programming language.

Program to print upto nth terms 

Using for loop

#include <iostream>
using namespace std;

int main()
{
    cout<<"Fibonacci series upto 10 terms :- "<<endl;
 
    int a = 0, b = 1;
    int next;

    for(int i=0; i<10; i++)
    {
        if(i==0) {
             cout<<a<<" ";
             continue;
        }

        else if(i==1)
        {
            cout<<b<<" ";
            continue;
        }

        next = a + b;
        a=b;
        b=next;

        cout<<next<<" ";
    }

    return 0;
}

Output:

Fibonacci series upto 10 terms :-
0 1 1 2 3 5 8 13 21 34

Time complexity of the above code is O(n) and space complexity is O(1).

The program will start from the main() function in the above code. Inside it first, the program asks the number of terms the user wants to enter. After taking the input in the 'num' variable, there are two variables, 'a' and 'b', which the first store initial value 0 and 1. The 'next' variable stores the sum of the previous two, i.e., values stored in variables a and b. For loop is used to move up to nth position and print values inside it.

The first and second iteration prints the value of a and b. The third iteration will assign the value of the 'next' variable, print it, and update the values of a and b, respectively.

Using while loop

#include <iostream>
using namespace std;

int main() {
    int num=10,next,a=-1,b=1;
     
    cout<<"Fibonacci series upto 10 terms :- "<<endl;
     
    while(num>0)
    {
        next=a+b;
        a=b;
        b=next;
        cout<<"  "<<next;
        num--;
    }
}

Output:

Fibonacci series upto 10 terms :-
0 1 1 2 3 5 8 13 21 34

It is the same program as the previous program whose task is to print Fibonacci series instead of using for loop, while loop is used. 

You practice by yourself with the help of online c++ compiler.

Recursion code for Fibonacci series

To take the program of printing the Fibonacci series to the next level, we will be doing the same task but with the help of recursion. Recursion is when a function calls itself again and again until its base case gets hit. Code is given below for the same.

Fibonacci series can be programed using recursion:-

#include <iostream>
using namespace std;
 
int fib(int n) {
   if((n==0)||(n==1)) {
      return(n);
   }else {
      return(fib(n-1)+fib(n-2));
   }
}
int main() {
   int i=0;
   cout << "\nFibonacci Series upto 10 terms :- "<<endl;
   while(i < 10) {
      cout << " " << fib(i);
      i++;
   }
   return 0;
}

Output :

Fibonacci Series upto 10 terms:-
 0 1 1 2 3 5 8 13 21 34

Time complexity of the above code is O(n) and space complexity is O(1).

In the above piece of code, the program starts running from the main() function, and after taking the input from the user, the fibo() function gets called. Inside the fibo() function, it first checks whether 'n' is less than or equal to 1 and if it is true, then returns else continues in the function. Later in the same function, there are two calls for the same function (function itself) for n-1 and n-2. It returns the sum of the returned value of previous function call statements. 

Also see, fibonacci series in c

Dynamic programming code for Fibonacci series

Recursion is good, but multiple irrelevant calls are made during recursion. So to make code more efficient, we use dynamic programming to achieve our task. We will print the Fibonacci series with the help of dynamic programming, i.e., dp. Code is given below.

#include<iostream>
using namespace std;

void fibonacci(int n) {
   int fibo[n+1];
   fibo[0] = 0;
   fibo[1] = 1;
   for (int i = 2; i <= n; i++) {
      fibo[i] = fibo[i-1] + fibo[i-2]; 
   }

   for(int j =0; j<n+1; j++)
        cout << fibo[j] << " ";
}

int main () {
    cout <<"Fibonacci Terms upto 10 terms :- "<<endl;
    fibonacci(10);
    return 0;
}

Output :

Fibonacci Series upto 10 terms:-
0 1 1 2 3 5 8 13 21 34

Time complexity of the above code is O(n) and space complexity is O(1).

We use dynamic programming to print the Fibonacci series in the above code. In the function fibonacci(), the first statement is a way to declare a dynamic array in C++, and here its length is one more than the user-entered value. Its size is one more because it has to hold the values from  0 to n, making a total n+1. After declaring the array, we add 0 and 1 in the 0th and 1st index of the same array. Then with the help of a for loop, we retrieve the value of the previous two values stored in dp, compute the current ith value, and return the final array. There is a simple print statement in the main() function to print the returned array from the function fibo(). 

Also readDecimal to Binary c++

FAQs

  1. What is the Fibonacci sequence?
    The Fibonacci series is the sequence of numbers in the form of 0 1 1 2 3 5 8 13 and so on.
     
  2. Can we print only the nth value of the Fibonacci series?
    Yes, by changing a few lines of the program, you can directly print the nth value of the series.
     
  3. While writing a dynamic programming program of the Fibonacci series, why do we take the size of dp as n+1?
    The size of dp must be taken as n+1 because we need to calculate and store the nth value of the Fibonacci series in the dp array.

Key Takeaways

In this article, we have extensively discussed the Fibonacci series and its implementation in C++. The blog contains the basic definition of the Fibonacci series and its implementation. Program to print this sequence will require a for or while loop. The dynamic programming method will be more helpful in making code more effective.

Check out this problem - Frog Jump

We hope that this blog has helped you enhance your knowledge regarding printing the Fibonacci series and if you would like to learn more, check out our articles on the Fibonacci sequence in Java. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass