C Recursion – A Complete Beginner's Guide

Recursion is a process in which a function calls itself to solve a smaller part of the problem. It’s commonly used for tasks that can be divided into similar sub-tasks like calculating factorials, traversing trees, or solving puzzles.

What is Recursion in C?

A recursive function is a function that calls itself, either directly or indirectly, to solve a problem.

 Syntax of Recursive Function

 
return_type function_name(parameters) {
if (base_condition)
return result;
else
return function_name(modified_parameters);
}

Example: Factorial using Recursion

#include <stdio.h>

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

int main() {
    int result = factorial(5);
    printf("Factorial = %d\n", result);
    return 0;
}

 Output:

Factorial = 120

How Recursion Works (Step-by-Step for factorial(3))

factorial(3)
→ 3 * factorial(2)
    → 2 * factorial(1)
        → 1 * factorial(0)
            → 1 (base case)
        → 1 * 1 = 1
    → 2 * 1 = 2
→ 3 * 2 = 6

Example: Fibonacci using Recursion

#include <stdio.h>

int fibonacci(int n) {
    if (n == 0)
        return 0;
    else if (n == 1)
        return 1;
    else
        return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
    int i, n = 7;
    printf("Fibonacci series: ");
    for (i = 0; i < n; i++) {
        printf("%d ", fibonacci(i));
    }
    return 0;
}

Output:

Fibonacci series: 0 1 1 2 3 5 8

Base Case is Important

Without a base case, the function would keep calling itself and cause a stack overflow error.

Add Your Heading Text Here

Best PracticeWhy It Matters
Always define a base casePrevents infinite recursion
Use recursion for divide-and-conquer problemsSimplifies the logic
Prefer iteration when possibleRecursion uses more memory (call stack)
Test with small inputs firstEnsures your logic is correct early

Common Mistakes in Recursion

MistakeProblem
Missing base caseLeads to infinite calls
Modifying parameters incorrectlyGives wrong results or crashes
Using recursion unnecessarilyWastes memory and processing time

Pros and Cons of Recursion

ProsCons
Simplifies complex problemsHigh memory usage (call stack)
Makes code elegant and cleanCan be slower than iteration
Useful in tree/graph problemsHard to debug if logic is wrong