C++ Program to Print the Fibonacci Sequence

In this program, we will learn how to make a C++ program of printing the Fibonacci Sequence. We will be learning two ways to make this program.

  1. Printing Fibonacci Sequence using loop
  2. Printing Fibonacci Sequence using Recursion

So, Let’s discuss these two ways one by one.

Printing Fibonacci Sequence using Loop

We will be using the for loop here.

Code:-

#include<iostream>

using namespace std;

int main(){
    // enter the number of terms of fibonacci sequence to print
    int n;
    cout << "Enter a number: ";
    cin >> n;   

    // stores the previous value
    int pre = 0;                                 
    // stores the current value
    int cur=1;                                   
    // loop to print n terms of fibonacci sequence
    for(int i=1; i<=n; i++){
        // prints the current value
        cout << cur << " ";                  
        // stores the current value to temp variable
        int temp=cur;                            
        // changes the current value by adding the prvious value to itself
        cur = cur + pre;                     
        // changes the previous value to temp value
        pre = temp;
    }
    return 0;                  
 
}
   

Output:-

Enter a number: 10
1 1 2 3 5 8 13 21 34 55

Printing Fibonacci Sequence using Recursion

Now, we will see how to make this program using Recursion.

Code:-

#include<iostream>

using namespace std;

// Recursive function to give fibonacci sequence
int fib(int n){
    if(n < 2){
        return n;
    }else{
        return fib(n-2) + fib(n-1);
    }    
}

int main(){
    // enter the number of terms of fibonacci sequence to print
    int n;
    cout << "Enter a number: ";
    cin >> n;   

    int i=1;
    while(i<=n){
        // Printing the fibonacci sequence
        cout << fib(i) << " ";
        i++;
    }
    return 0;                  
 
}
   

Output:-

Enter a number: 8
1 1 2 3 5 8 13 21

You can learn about many other C++ Programs Here.







The following two tabs change content below.

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...