Recursive functions

Home / C Programming / Recursive functions

Recursive functions


In C programming, a recursive function is a function that calls itself within its own definition. This technique is used to solve problems that can be broken down into smaller, similar subproblems. Recursive functions provide an elegant way to solve certain types of problems, but they should be used with caution, as they can lead to stack overflow errors if not handled properly.

A recursive function typically has two components:

1. Base case(s): These are the stopping conditions that prevent the function from calling itself further. Base cases are essential to avoid infinite recursion and to ensure the termination of the recursive process.

2. Recursive step: This is the part of the function where it calls itself with a smaller or simpler version of the problem. The recursive call works towards reaching the base case, which eventually leads to the termination of the recursion.

Here's an example of a simple recursive function to calculate the factorial of a positive integer:

#include <stdio.h>

// Recursive function to calculate factorial

int factorial(int n) {

    // Base case: factorial of 0 and 1 is 1

    if (n == 0 || n == 1) {

        return 1;

    } else {

        // Recursive step: n! = n * (n-1)!

        return n * factorial(n - 1);

    }

}

int main() {

    int num = 5;

    int result = factorial(num);

    printf("Factorial of %d is %d\n", num, result);

    return 0;

}

When you call `factorial(5)` in the `main` function, the recursive calls are as follows:

factorial(5) -> 5 * factorial(4)

factorial(4) -> 4 * factorial(3)

factorial(3) -> 3 * factorial(2)

factorial(2) -> 2 * factorial(1)

factorial(1) -> 1 (base case)

The recursive calls will then start unwinding, with each result being multiplied along the way, eventually leading to the final result:

factorial(1) -> 1

factorial(2) -> 2 * 1 = 2

factorial(3) -> 3 * 2 = 6

factorial(4) -> 4 * 6 = 24

factorial(5) -> 5 * 24 = 120

That's how the factorial of 5 is calculated using recursion.