fbpx

How Recursive Functions Work in C?

Recursive functions in c

INTRODUCTION

Recursive functions in C are a powerful programming tool that allows tasks to be broken down into smaller, manageable pieces. They work by having a function call itself to solve sub-problems, mimicking processes like tracing ancestry or cutting a pizza into smaller slices.

Recursion relies on two key elements:

  1. Base Case: The condition where the recursion stops.
  2. Recursive Case: The step where the function keeps calling itself to move closer to the base case.

For example, calculating the sum of natural numbers, finding a factorial, or generating a Fibonacci series are classic uses of recursion. Each problem is solved step-by-step until the base case is reached, making recursion a clean and elegant solution for many tasks.

Explore the examples of recursive functions in C to see this concept in action and understand how it simplifies complex problems!

Recursive functions in c:

  • Doing the work Parallely

 Scenario: To trace your ancestry, you look at your parents, then their parents, and so on, until you reach the earliest known ancestor.

  • Recursion Analogy:
    • Base case: The earliest ancestor is found (no parents to trace further).
    • Recursive case: Check the parents of the current person and repeat the process.

Cutting a Pizza

  • Scenario: Cutting a pizza into smaller and smaller slices. Each slice is further divided until the pieces are small enough to eat.
  • Recursion Analogy:
    • Base case: A slice is small enough to eat.
    • Recursive case: Divide the current slice into smaller parts.

Examples in Recursive functions in c:

_______________________________

Sum of n natural numbers:

———————————

#include <stdio.h>

int sum(int n)

{

    if(n==1)

        return 1;

    else

        return n+sum(n-1);

}

int main()

 {

    int no=sum(5);

    printf(“%d”,no);

}

Product of  n natural numbers:

#include <stdio.h>

int sum(int n)

{

    if(n==1)

        return 1;

    else

        return n*sum(n-1);

}

int main()

 {

    int no=sum(5);

    printf(“%d”,no);

}

Fibonacci series:

#include <stdio.h>

int sum(int n)

{

    if(n==0)

        return 0;

    else if(n==1)

        return 1;

    else

        return sum(n-1)+sum(n-2);

}

int main()

 {

    int no=sum(5);

    printf(“%d”,no);

}