C program to generate nth fibonacci term using recursion

Write a recursive function to generate nth fibonacci term in C programming. How to generate nth fibonacci term in C programming using recursion.
Fibonacci series pattern

Example:
Input any number: 10
Output 10th fibonacci term: 55

Required knowledge

Basic C programming, Function, Recursion, Fibonacci series

Logic 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

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 ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment