C programming - Recursion

h‮sptt‬://www.theitroad.com

Recursion in C programming is a technique in which a function calls itself repeatedly until a base case is reached. Recursion is a powerful programming technique that can be used to solve many problems in a more elegant and efficient way than other approaches.

A recursive function consists of two parts: a base case and a recursive case. The base case is a condition that stops the recursion and returns a value, while the recursive case is the part of the function that calls itself.

Here's an example of a recursive function in C that calculates the factorial of a given number:

int factorial(int n)
{
    if(n == 0)
        return 1;   // base case
    else
        return n * factorial(n-1);  // recursive case
}

In this example, the factorial function takes an integer argument n and calculates the factorial of n using recursion. If n is equal to 0, the function returns 1, which is the base case. If n is greater than 0, the function calls itself with the argument n-1, which is the recursive case.

When the factorial function is called with a non-negative integer argument, it calculates the factorial using recursion until the base case is reached. For example, if you call the factorial function with the argument 5, the function will execute as follows:

factorial(5)
    -> return 5 * factorial(4)
        -> return 4 * factorial(3)
            -> return 3 * factorial(2)
                -> return 2 * factorial(1)
                    -> return 1 * factorial(0)
                        -> return 1 (base case)

The final result is the factorial of 5, which is 120.