Home C++ Tutorial C++ Program to Find Fibonacci Series

C++ Program to Find Fibonacci Series

by Krishna Jaiswal
32 minutes read

In this article, you’ll learn about how to make C++ Program to Find Fibonacci Series.

What is the Fibonacci Series?

Series 0, 1, 1, 2, 3, 5, 8, 13, 21 . . . . . . . is a Fibonacci series. In Fibonacci series, each term is the sum of the two preceding terms.

Program for Fibonacci Series up to n number of terms

#include <iostream>
using namespace std;

int main() {
    int n, t1 = 0, t2 = 1, nextTerm = 0;

    cout << "Enter the number of terms: ";
    cin >> n;

    cout << "Fibonacci Series: ";

    for (int i = 1; i <= n; ++i) {
        // Prints the first two terms.
        if(i == 1) {
            cout << t1 << ", ";
            continue;
        }
        if(i == 2) {
            cout << t2 << ", ";
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        
        cout << nextTerm << ", ";
    }
    return 0;
}

Output

Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 

Program for Fibonacci Series up to n number of terms using Recursion

#include <iostream>
using namespace std;
int fib(int x) {
   if((x==1)||(x==0)) {
      return(x);
   }else {
      return(fib(x-1)+fib(x-2));
   }
}
int main() {
   int x , i=0;
   cout << "Enter the number of terms of series : ";
   cin >> x;
   cout << "\nFibonnaci Series : ";
   while(i < x) {
      cout << " " << fib(i);
      i++;
   }
   return 0;
}

Output

Enter the number of terms of series : 14
Fibonnaci Series : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 

Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

related posts

Leave a Comment