Fibonacci Series in C++

Program to print Fibonacci series up to N  numbers

Here we will discuss how to find the Fibonacci Series upto n numbers using C++ Programming language. We will look at different ways of coding Fibonacci Series in C++

fibannoci series upto n terms in c++

What is Fibonacci Series

Method Discussed

  • Method 1: Simple iterative
  • Method 2: Recursive with a static variable
  • Method 3: Recursive without static variable
  • Method 4: Using Dynamic Programming

Objective: Write a program to print fibonacci series in C++

Fibonacci Series in C++

Method 1

C++ Code

Run
// Write a program to print fibonacci series in C++
#include <iostream>
using namespace std;

int main()
{
    int num = 15;
    int a = 0, b = 1;
    
    // Here we are printing 0th and 1st terms
    cout << a << ", " << b << ", ";
    
    int nextTerm;
    
    // printing the rest of the terms here
    for(int i = 2; i < num; i++){
        nextTerm = a + b;
        a = b;
        b = nextTerm;
        
        cout << nextTerm << ", ";
    }

    return 0;
}

Output

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

Method 2

For the below are have used –

C++ Code

Run
#include <iostream>
using namespace std;

int Fib(int n){
    
    // Note : declaring static items too here
    static int t1 = 0, t2 = 1, nextTerm;
    
    if(n > 0)
    {    
        nextTerm = t1 + t2;
        t1 = t2;    
        t2 = nextTerm;    
    
        cout << nextTerm << ", ";    
        Fib(n-1);    
    }
    
}

int main()
{
    int n = 15;
    
    cout << "0, 1, ";
    
    // n-2 as 2 terms already printed
    Fib(n-2);

    return 0;
}

Output

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

Method 3

The previous method used Static variables in C++, which sometimes is undesirable to do so.

The following method only uses Recursion in C++ and not static methods –

C++ Code

Run
#include <iostream>
using namespace std;

int fibonacci(int n){
    
    if(n <= 1)
        return n;
        
    return fibonacci(n-1) + fibonacci(n-2);
    
}

int main()
{
    int n = 15;

    for(int i = 0; i < n; i++)
        cout << fibonacci(i) << ", ";

    return 0;
}

Output

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

Method 4

This method uses dynamic programming concept.

C++ Code

Run
#include <iostream>
using namespace std;

void fib(int n)
{

    int f[n + 1];

    f[0] = 0;
    f[1] = 1;
    
    cout << f[0] << ", " << f[1] <<", ";
    
    for (int i = 2; i < n; i++)
    {
        f[i] = f[i - 1] + f[i - 2];
        cout << f[i] <<", ";
    }
}
 
int main()
{
    int n = 10;
    
    fib(n);
    
    return 0;
}

Output

0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription