C++ Program to Display Fibonacci Series using Loop and Recursion

C++ Program to display fibonacci series using recursion.


C++ program to print fibonacci series using loop

#include <iostream>

using namespace std;
 
int main(){
    int N, last=1, secondLast=0, current=0, i;
    cout << "Enter number of terms in Fibonacci series\n";
    cin >> N;
    /*
     *  N term = (N-1)th therm + (N-2)th term;
     * or  current term = last term + secondLast term;
     */
    for(i = 0; i < N; i++){
        if(i < 2){
            current = i;
        } else {
            current = last + secondLast;
            secondLast = last;
            last = current;
        }
        cout << current << " ";
    }
    return 0;
}
Output
Enter number of terms in Fibonacci series
8
0 1 1 2 3 5 8 13

C++ program to print fibonacci series using recursion

#include <iostream>

using namespace std;
 
int fibonacci(int term){
    if(term < 2)
       return term;
    return fibonacci(term -1) + fibonacci(term - 2);
}

int main(){
    int N, i;
    cout << "Enter number of terms in Fibonacci series\n";
    cin >> N;
    /*
     *  Nth term = (N-1)th therm + (N-2)th term;
     */
    for(i = 0; i < N; i++){
        cout << fibonacci(i) << " ";
    }
    return 0;
}
Output
Enter number of terms in Fibonacci series
9
0 1 1 2 3 5 8 13 21

Recommended Posts
C++ Program to Print Floyd Triangle
C++ Program to Print Pascal Triangle
C++ Program to Add Two Distances in Inch and Feet
C++ Program to Multiply Two Matrices
C++ Program to Find Power of Number using Recursion
C++ Program to Display Factors of a Number
C++ Program to Reverse Digits of a Number
C++ Program to Find All Square Roots of a Quadratic Equation
C++ Program to Swap Numbers in Cyclic Order
All C++ Programs