C++ program to display Fibonacci series using loop and recursion

In this example, you will learn about C++ program to display Fibonacci series of first n numbers (entered by the user) using the loop and recursion.

C++ program to display Fibonacci series using loop and recursion
C++ program to display Fibonacci series using loop and recursion

Fibonacci Series: It is a series of numbers where the next term in series is the sum of previous two numbers.

Fibonacci Series: 0 1 1 2 3 5 8 13 ...

Here is the program to display Fibonacci series in C++.

Example: C++ program to display Fibonacci series using loop

//C++ program to implement Fibonacci series

#include<iostream>
using namespace std;

int main()
{
   int oldNum, newNum, fibNum, maxNum;

   //Enter maximum number till you want to generate Fibonacci series
   cout << "Enter number: ";
   cin >> maxNum;

   oldNum = 0;
   newNum = 1;
   fibNum = oldNum + newNum;

   cout << "\nFibonacci Series: " << oldNum << " " << newNum;

   //while is true till fibNum is less than maxNum and fibNum is calculated
   while(fibNum <= maxNum)
   {
      cout << " " << fibNum;
      oldNum = newNum;
      newNum = fibNum;
      fibNum = oldNum + newNum;
   }

   cout << "\n";
   return 0;
}

Output

fibonacci series in C++

Example: C++ program to display Fibonacci series using recursion

//C++ program to display Fibonacci series using recursion

#include<iostream>
using namespace std;

int fibonacci(int n);  //function declaration

int main()
{
   int num, fibNum, i;

   //Enter the total number in series
   cout << "Enter the number of terms: ";
   cin >> num;

   fibNum = 0;

   cout << "\nFibonacci Series: ";

   for(i = 1; i <= num; i++)
   {
      cout << " " <<fibonacci(fibNum); //calling recursive function
      fibNum++;
   }

   cout << "\n";
   return 0;
}

//recursive function for Fibonacci series
int fibonacci(int n)
{
   if(n == 0)
      return 0;
   else if (n == 1)
      return 1;
   else
    return(fibonacci(n-1) + fibonacci(n-2)); //calling itself
}

Output

fibonacci series program in C++ using recursion

Explanation

In this program, we have used recursive function fibonacci() to display Fibonacci series.

This program will display num number of terms in Fibonacci series.