In a previous post, i explained how to write a program to print fibonacci series using iteration. In this post, i’ll help you implement the same using recursion.

Here are the facts we use in our program:

1st number in Fibonacci series = 0

2nd number in Fibonacci series = 1

nth number in Fibonacci series = (n-1)th number + (n-2)th number

Now we’ll simply create a function with one parameter and just impement the above facts in the function. Here is the program:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include<iostream> using namespace std; int fibonacci(int); int main() { int n; /* Read input from user */ cout<<"Enter the number of terms: "; cin>>n; /* Print the series */ for(int i=1; i<=n; ++i) cout<<fibonacci(i)<<" "; return 0; } /* Function to find nth number in fibonacci series */ int fibonacci(int n) { if(n==1) return 0; //first number = 0 else if(n==2) return 1; //second number = 1 else return (fibonacci(n-1) + fibonacci(n-2)); } |