Example:
Input any number: 10
Output 10th fibonacci term: 55
Required knowledge
Basic C programming, Function, Recursion, Fibonacci seriesLogic to find nth Fibonacci term
In one of my previous post I had already explained what is Fibonacci number and how to generate Fibonacci series using for loop. Here in this post I will be explaining how to generate nth Fibonacci term using recursion. When talking about recursive function we must be clear with the base condition of the recursion which is explained below.fibo(0) = 0 {Base condition}
fibo(1) = 1 {Base condition}
fibo(num) = fibo(num-1) + fibo(num+2)
Program to find nth fibonacci term
/** * C program to find nth Fibonacci term using recursion */ #include <stdio.h> //Function declaration long long fibo(int num); int main() { int num; long long fibonacci; //Reads number from user to find nth fibonacci term printf("Enter any number to find nth fiboacci term: "); scanf("%d", &num); fibonacci = fibo(num); printf("%dth fibonacci term is %lld", num, fibonacci); return 0; } /** * Recursive function to find nth Fibonacci term */ long long fibo(int num) { if(num == 0) //Base condition return 0; else if(num == 1) //Base condition return 1; else return fibo(num-1) + fibo(num-2); //Recursively calls fibo() to find nth fibonacci term. }
Output
Enter any number to find nth fiboacci term: 10
10th fibonacci term is 55
10th fibonacci term is 55
Note: Some compilers doesn't supports long long type so you may replace it with long and the format specifier with %ld to overcome the compilation error if any.
Happy coding ;)
You may also like
- Function and recursion programming exercises index.
- C program to find factorial of any number using recursion.
- C program to find GCD (HCF) of any two numbers using recursion.
- C program to find LCM of any two numbers using recursion.
- C program to find power of any number using recursion.
- C program to find cube of any number using function.
- C program to find reverse of any number using recursion.
- C program to check palindrome numbers using recursion.
- C program to find sum of digits using recursion.
- C program to display all elements of array using recursion.
- C program to find sum of elements of array using recursion.