In this article
Recursion is when a function calls itself to solve a problem, breaking it into smaller and smaller versions of the same problem, until it reaches a case so simple that the answer is immediate. That simple case is called the base case.
In the article on functions, you saw that a function can be called as many times as you want. Today’s question is: what if it calls itself? Sounds crazy, I know haha. But don’t worry! In the end, it’s all pretty simple.
How does recursion work?
Think of Russian dolls, the ones that have a smaller doll inside another. To get to the last one, you open one, find another one just like it, only smaller, and open it again, until you reach the doll that doesn’t open anymore. That last one is the base case. Then you close them all, one by one, going back the same way.

Every recursive function has two parts, and you need BOTH:
- Base case: the condition that says when to stop.
- Recursive call: the function calls itself, always with a smaller problem than the one before.
What is a factorial?
Before the code, let’s meet the star of our example. The factorial comes from math: it’s the product of a natural number and all the numbers that come before it, down to 1. Its symbol is the exclamation mark, placed after the number. Like this:
- 3! = 3 × 2 × 1 = 6
- 4! = 4 × 3 × 2 × 1 = 24
- 5! = 5 × 4 × 3 × 2 × 1 = 120
No, math isn’t shouting at you. 5! is just the short way to write the whole multiplication.
One detail: by definition, 0! = 1. And notice how fast the factorial grows: 10! is already 3,628,800, and 20! is 2,432,902,008,176,640,000.
What is the factorial used for in practice?
To count possibilities. Here are three uses:
- Putting things in order (permutations): n different items can be lined up in n! ways. Three books, A, B and C, fit on the shelf in 3! = 6 orders: ABC, ACB, BAC, BCA, CAB and CBA. Six people in a line: 6! = 720 orders.
- Making anagrams: the 5 letters of the word EARTH can be shuffled in 5! = 120 ways.
- Choosing groups (combinations): when the order doesn’t matter, the formula is n! ÷ (k! × (n − k)!), where k is the size of the group. Choosing 4 employees out of 10 gives 210 groups. Choosing 6 numbers out of 60 gives 50,063,860 combinations.
These counts are the first step in calculating probabilities: to know the chance of an outcome, you first need to count how many outcomes there are.
In programming, the factorial shows up when a program needs to test every possible order of something. With 10 items, that’s 3,628,800 orders. With 20, the number already has 19 digits. “Test everything” stops being an option very quickly.
Python already has this calculation built in: math.factorial(5) returns 120. But today we’re going to write our own, because the factorial has a feature that matters a lot for this article.
Recursion example: the factorial
The factorial is the classic recursion example, and now you’ll see why. Look closely at the calculation: 5! = 5 × 4 × 3 × 2 × 1. The part 4 × 3 × 2 × 1 is 4!. In other words, 5! = 5 × 4!. In the same way, 4! = 4 × 3!, and so on. The problem contains a smaller version of itself! It’s the doll inside the doll. The base case is 1!, which equals 1 and needs no calculation at all. Here it is in PHP:
<?php
function factorial(int $n): int
{
if ($n <= 1) {
return 1; // base case: this is where the function stops calling itself
}
return $n * factorial($n - 1); // recursive call
}
echo factorial(5), PHP_EOL; // 120
In Python:
def factorial(n):
if n <= 1:
return 1 # base case: this is where the function stops calling itself
return n * factorial(n - 1) # recursive call
print(factorial(5)) # 120
And in C:
#include <stdio.h>
int factorial(int n) {
if (n <= 1) {
return 1; // base case: this is where the function stops calling itself
}
return n * factorial(n - 1); // recursive call
}
int main(void) {
printf("%d\n", factorial(5)); // 120
return 0;
}
IMPORTANT: remember that the factorial grows fast? That shows up in the code. I tested it here: in the C version, with the 4-byte int type, the result is right up to 12! (479,001,600). 13! is 6,227,020,800, which no longer fits in the variable, and factorial(13) printed a wrong number: 1932053504. In the PHP version, factorial(20) worked, and factorial(21) stopped with TypeError: factorial(): Return value must be of type int, float returned. In Python, factorial(21) returned 51090942171709440000, with no error.
What happens inside a recursive function?
Here’s factorial(4) step by step:
| Step | Call | What it does |
|---|---|---|
| 1 | factorial(4) | Waits for the result of factorial(3) |
| 2 | factorial(3) | Waits for the result of factorial(2) |
| 3 | factorial(2) | Waits for the result of factorial(1) |
| 4 | factorial(1) | Base case: returns 1 |
| 5 | factorial(2) | Returns 2 × 1 = 2 |
| 6 | factorial(3) | Returns 3 × 2 = 6 |
| 7 | factorial(4) | Returns 4 × 6 = 24 |
Do you see how the calls pile up and are then resolved in reverse order? The computer keeps each call on a stack: the last one in is the first one out.

See the animation of the call stack of factorial(4)

What happens if I forget the base case?
The function never stops calling itself, the stack fills up and the program crashes. Look at this Python function, with no base case:
def countdown(n):
print(n)
countdown(n - 1) # no base case: it never stops
countdown(3)
I tested it here, and the program ended with the error RecursionError: maximum recursion depth exceeded. In PHP, the official manual warns that infinite recursion is considered a programming error, and that recursive calls with more than 100 to 200 levels can already exhaust the stack and end the script.
Now it’s your turn!
Write a recursive function that adds up all the numbers from 1 to n. For n = 4, the result is 10 (4 + 3 + 2 + 1). Before typing, answer on paper: what is the base case? And what is the recursive call?
If you answered those two questions, the code is already done in your head!!! Try it on your own before asking anyone for the answer. Using your own reasoning is how you really learn.
Recursion or a loop?
Anything you do with recursion can be done with a loop, and vice versa. So when should you use each one?
| Recursion | Loop | |
|---|---|---|
| Good fit for | Problems that split into equal, smaller parts, like folders inside folders | Simple repetitions, with a known start and end |
| Memory | Uses the stack on every call | Uses less memory |
| Reading | Usually shorter | More straightforward for beginners |
For the factorial, to be honest, the loop does a better job. I used this example because it’s the easiest one to see. Recursion really shines when we get to trees and to search and sorting algorithms.
And that’s where we’re headed! In the next article, you’ll meet linear search, the simplest way to find a value in an array. After that comes binary search, a much faster way. See you there!
Stay confident!!!
Sources:
- Princeton University, Computer Science: An Interdisciplinary Approach (Robert Sedgewick and Kevin Wayne), COS 126. 2.3 Recursion, with the factorial as the classic example, the base case 1! = 1, the reduction step n! = n × (n − 1)! and the bug of a reduction step that never reaches the base case (PDF).
- UC Berkeley, Composing Programs (John DeNero), the CS 61A textbook. 1.7 Recursive Functions, with a function being recursive when its body calls the function itself, and the recursive factorial compared with the iterative one.
- Runestone Academy, Problem Solving with Algorithms and Data Structures using Python. 4.4 The Three Laws of Recursion, with the base case, the change of state that moves toward it and the call of the algorithm to itself.
- MIT, 6.102 Software Construction. Recursion review, with base cases, recursive cases that move toward them and 0! = 1 by definition.
- MIT, 6.102 Software Construction. Recursion and iteration review, with the same functions written both ways and recursion limited by a maximum call-stack depth in languages like Python.
- Stanford University, CS106B. Recursion: factorial, with the base case, the recursive case and the call stack, where each call pushes a stack frame and each return pops it (PDF).
- Stanford University, CS106B. Recursion warmup, with the stack overflow that happens when stack frames keep growing until they use up the memory set aside for the call stack.
- University of California, Berkeley, CS 4 (Jonathan Shewchuk). Lecture 17, with the frames of factorial piling up on the stack until factorial(1), the base case, returns 1 without calling factorial again.
- PHP Manual. User-defined functions, with the note that recursive calls with more than 100 to 200 levels can exhaust the stack and end the script, and that infinite recursion is considered a programming error.
- PHP Manual. Integers, with operations whose result goes beyond the limits of the int type returning a float.
- Python documentation. Built-in Exceptions, with
RecursionError, raised when the interpreter detects that the maximum recursion depth is exceeded. - Python documentation. sys, with
sys.getrecursionlimit(), the maximum depth of the interpreter stack, a limit that keeps infinite recursion from crashing Python. - Python documentation. math, with
math.factorial(), which returns the factorial of a nonnegative integer. - UC Berkeley, Department of Statistics, SticiGui (Philip B. Stark). Counting, with n! as the number of possible orderings of n things, 0! = 1 by convention, and the formulas for permutations and combinations.
- The examples in this article were run on Python 3.13, PHP 8.3 and GCC 13.

Continue the conversation