HOME HTML EDITOR C JAVA PHP

C Recursion: Functions That Call Themselves

**Recursion** is the process of defining something in terms of itself. In C, a recursive function is one that includes a call to itself within its own body. Every recursive solution must have a way to stop; otherwise, it will continue indefinitely, leading to a "Stack Overflow."

1. The Anatomy of a Recursive Function

To prevent a function from calling itself forever, every recursive function must have two essential parts:

2. Classic Example: Calculating Factorial

The factorial of a number $n$ (denoted as $n!$) is the product of all positive integers less than or equal to $n$. Mathematically, $n! = n \times (n-1)!$.

#include <stdio.h>

int factorial(int n) {
    if (n <= 1) { // Base Case
        return 1;
    }
    else { // Recursive Case
        return n * factorial(n - 1);
    }
}

int main() {
    printf("Factorial of 5 is: %d", factorial(5));
    return 0;
}

3. How Recursion Works in Memory

When a function calls itself, the computer doesn't "restart" the function. Instead, it pushes a new Stack Frame onto the "Call Stack." Each frame stores the unique variables and return address for that specific call.

Once the base case is reached, the functions begin returning their values one by one, "unwinding" the stack until the final result reaches the original caller (usually main()).

4. Recursion vs. Iteration (Loops)

Anything you can do with recursion, you can also do with a for or while loop. Choosing between them depends on the problem.

Feature Recursion Iteration
Code Size Compact and elegant. Often longer and more complex.
Memory Usage High (uses stack space). Low (reuses same memory).
Speed Slower (call overhead). Faster.

5. The Danger: Stack Overflow

If your base case is missing or incorrect, the function calls itself until the computer runs out of stack memory. This results in a Stack Overflow error, which immediately crashes your program.

6. When to Use Recursion?

Pro Tip: In professional C development, always check for "Tail Recursion." Some modern compilers can optimize a recursive function into a loop if the recursive call is the very last thing the function does. This gives you the elegance of recursion with the performance of a loop!