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

  • Write a C++ program to print fibonacci numbers using for loop.
  • 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;
 
/*
 * Funtion to calculate Nth Fibonacci number
 * fibonacci(N) = fibonacci(N - 1) + fibonacci(N - 2);
 */
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