HomeC ProgrammingC Program to Find Nth Fibonacci Number using Recursion

C Program to Find Nth Fibonacci Number using Recursion

Introduction

This C program calculates the Nth Fibonacci number using recursion. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones. The program uses a recursive function to calculate the Nth Fibonacci number.

Problem statement

Write a C program to find the Nth Fibonacci number using recursion.

C Program to Find Nth Fibonacci Number using Recursion

#include <stdio.h>

int fibonacci(int n)
{
    if (n <= 1)
        return n;
    else
        return fibonacci(n - 1) + fibonacci(n - 2);
}

int main()
{
    int n;
    printf("Enter the value of N: ");
    scanf("%d", &n);
    
    int result = fibonacci(n);
    printf("The %dth Fibonacci number is: %d\n", n, result);
    
    return 0;
}

How it works

  1. The program defines a function fibonacci() that takes an integer n as a parameter and returns the Nth Fibonacci number.
  2. In the fibonacci() function, there is a base case where if n is less than or equal to 1, it returns n itself (0 for n=0 and 1 for n=1).
  3. For values of n greater than 1, the function recursively calls itself with n-1 and n-2, and adds the results to get the Fibonacci number.
  4. In the main() function, the user is prompted to enter the value of N.
  5. The scanf() function is used to read the input value from the user and store it in the variable n.
  6. The fibonacci() function is called with the input value n to calculate the Nth Fibonacci number.
  7. The result is then printed on the console.

Input/Output

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...