0
0
CConceptBeginner · 3 min read

What is Recursive Function in C: Explanation and Example

A recursive function in C is a function that calls itself to solve smaller instances of the same problem until it reaches a base case. It helps break down complex tasks into simpler steps by repeating the function with new inputs.
⚙️

How It Works

Think of a recursive function like a set of Russian nesting dolls. Each doll contains a smaller doll inside it, and you keep opening them until you reach the smallest one. Similarly, a recursive function calls itself with a simpler or smaller input each time.

Each call waits for the next call to finish before it can complete. This continues until the function reaches a base case, which is a condition that stops the recursion. Without a base case, the function would call itself forever, causing the program to crash.

💻

Example

This example shows a recursive function that calculates the factorial of a number. The factorial of 5 (written as 5!) is 5 × 4 × 3 × 2 × 1 = 120.

c
#include <stdio.h>

int factorial(int n) {
    if (n == 0) {
        return 1;  // Base case: factorial of 0 is 1
    } else {
        return n * factorial(n - 1);  // Recursive call
    }
}

int main() {
    int number = 5;
    printf("Factorial of %d is %d\n", number, factorial(number));
    return 0;
}
Output
Factorial of 5 is 120
🎯

When to Use

Recursive functions are useful when a problem can be divided into similar smaller problems. Examples include calculating factorials, Fibonacci numbers, searching in tree structures, and solving puzzles like the Tower of Hanoi.

They make code simpler and easier to understand for problems that have repetitive patterns. However, recursion can be less efficient than loops for some tasks, so it’s best used when the problem naturally fits this approach.

Key Points

  • A recursive function calls itself with simpler inputs.
  • It must have a base case to stop the recursion.
  • Useful for problems that break down into similar smaller problems.
  • Can simplify code but may use more memory than loops.

Key Takeaways

A recursive function solves a problem by calling itself with smaller inputs.
Always include a base case to prevent infinite recursion.
Recursion is ideal for problems with repetitive, self-similar structure.
Recursive code can be simpler but may use more memory than loops.