How to find the nth term of the Fibonacci series using recursion
Fibonacci series
Let’s first see what the Fibonacci series is:
The Fibonacci series generally starts with 1 and 1 as default, which means that the first and second term is always 1.
The series looks like this:
1,1,2,3,5,8,13...
We can see that the first and the second term is one, and the succeeding term is calculated by the addition of the previous two terms.
So to get the sequence, we need to add the previous two elements. The sequence will be generated in the same way throughout the process.
In this shot, we’ll implement the Fibonacci series using recursion.
Note: Recursion is the process in which the function calls itself. We use recursion here to implement the term of the Fibonacci series.
Example
The 1st term of the Fibonacci series is 1.
- Here
nis 1 so ifn==1||n==2we return the value 1.
The 5th term of the Fibonacci series is 5.
- Here, n is 5, so we call
fib(n-1)+fib(n-2)recursively to get the value 5.
Algorithm
-
If
nis 0, then return 0. -
If
nis 1 or 2, we return 1. -
Otherwise, we use
fib(n-1)+fib(n-2), which will be called recursively throughout the process.
Pseudocode
if(n==0 or n==1)
{
return 1
}
return fib(n-1)+fib(n-2);
#include<stdio.h>int fib(int); // Function declarationint main(){int n; // Declaration of variablescanf("%d",&n);printf("The %d term in the fibnoci series is: %d ",n,fib(n)); // Calling function}int fib(int n) // Function declaration{if(n==0){return 0;}if(n==1||n==2){return 1;}return fib(n-1)+fib(n-2); // Recursive funnction}
Enter the input below
Explanation
First, we read the value of n.
-
Line 2: We declare
int fib(int). -
Line 7: We call the function
fib(n). -
Line 9: We declare the function.
-
Line 11–14: If
nis0, we return0. -
Line 15–18: If
nis1or2, we return1. -
Line 19: If
nis something other than0,1, or2then we callfib(n-1)+fib(n-2)recursively.