English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C ++Program Uses Recursion to Find Fibonacci Numbers

The following is an example of the Fibonacci sequence using recursion.

Example

#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 result

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

In the above program, the actual code exists in the function "fib" as follows:

if((x ==1) || (x == 0)) {
   return(x);
} else {
   return(fib(x-1)+fib(x-2));
}

in thismain()In the method, the user input andfib()Called multiple terms. The Fibonacci series is printed as follows.

cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
   cout << " " << fib(i);
   i++;
}