Print fibonacci series using C++

Before print fibonacci series we have to know what a fibonacci series is. Fibonacci series is a series whose first two numbers are 0 and 1 and any other number is equal to the sum of previous two numbers. Let’s see the fibonacci series bellow;

0   1   1   2   3   5   8   13   21   34   55 . . . . . . . .

In C programming we have discussed about several programming related to Fibonacci series in C. Here we will see some program related to fibonacci series using C++. Let’s see the program to print fibonacci series in C++.

Program to print Fibonacci series

The bellow program will take the input from user that how many number he want to print of fibonacci series. Then it will print the given number of element of the fibonacci series.

// printing fibonacci series in c++

#include <iostream>
using namespace std;

int main(){
    int c, total, first_number = 0, second_number = 1, nums;
    
    cout << "Enter how many element you want to print : ";
    cin >> total;
    
    cout << first_number << " " << second_number << " " ;
    
    for(c = 2; c < total; ++c){
        nums = first_number + second_number;
        cout << nums << " ";
        first_number = second_number;
        second_number = nums;
    }
    
    return 0;
    
}

Output of Fibonacci series program

fibonacci-series-in-c-c-fibonacci-series-printing-program

Fibonacci series using recursion in C++

In this program we will use recursion to print fibonacci series. As our first program, here also we will take the input from user that how many element he want to print and then the program will print the fibonacci series.

// printing fibonacci series with recursion in c++

#include<iostream>
using namespace std;

void fibonacci_series(int nums){    // function to print fibonacci series
    static int first = 0, second = 1, others;

    if(nums > 0){
         others = first + second;
         first = second;
         second = others;

         cout << others << " ";

         fibonacci_series(nums - 1);
    }
}

int main(){
    int total_num;

    cout << "Enter how many element you want : ";
    cin >> total_num;

    cout << "0 " << "1 ";    // printing 0 and 1 as first two element

    fibonacci_series(total_num - 2);    // as two number 0 and 1 have already printed

    return 0;
}

Output fibonacci series:

Enter how many element you want : 10
0 1 1 2 3 5 8 13 21 34

Previous pageSwap number

Next pagePalindrome number