Course contentsShow
← C
Lesson 357 of 1,2195. FunctionsFree lesson

Factorial as a recursive example

Factorial as a recursive example

What you'll learn: How to solve a mathematical problem by having a function call itself with a smaller version of the same task.

The Russian Nesting Doll

Recursion can feel like a brain-bender, but it follows a simple pattern: to solve a big problem, you break it down into a slightly smaller version of itself. Think of a Russian nesting doll. To get to the tiny solid doll in the center, you must first open the largest one, then the middle one, and so on.

In mathematics, the factorial of a number (written as n!n!) is a perfect example.

  • 5!5! is 5×4×3×2×15 \times 4 \times 3 \times 2 \times 1.
  • Notice that 4×3×2×14 \times 3 \times 2 \times 1 is actually just 4!4!.
  • Therefore, 5!=5×4!5! = 5 \times 4!.

This is the heart of recursion. We define the factorial of a number as that number multiplied by the factorial of the number right below it.

Writing it in C

When writing a recursive function, you need two things:

  1. The Base Case: The "smallest doll" where the recursion stops (e.g., 1!=11! = 1).
  2. The Recursive Step: The part where the function calls itself.
#include <stdio.h>

int factorial(int n) {
    // 1. The Base Case
    if (n <= 1) {
        return 1;
    }
    
    // 2. The Recursive Step
    // We multiply n by the result of factorial(n - 1)
    return n * factorial(n - 1);
}

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

How the computer sees it

When you call factorial(5), the computer doesn't get an answer immediately. It "pauses" the calculation of 5 and moves inside to calculate factorial(4). This continues until it reaches factorial(1).

Once it hits the Base Case (1), it finally has a solid number. It then passes that result back up the chain. It calculates 2×12 \times 1, then 3×23 \times 2, then 4×64 \times 6, and finally 5×245 \times 24. The "stack" of paused functions collapses, delivering the final answer of 120.

Without that base case, the function would call itself forever (or until the program crashes), like a mirror reflecting another mirror into infinity.

Key takeaway

Recursion is a process where a function calls itself to solve a smaller piece of the puzzle, eventually stopping at a base case.