Algorithms

Recursion: a function that calls itself (and knows when to stop)

Cover of the article Recursion: a function that calls itself (and knows when to stop)
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. How does recursion work?
  2. What is a factorial?
  3. What is the factorial used for in practice?
  4. Recursion example: the factorial
  5. What happens inside a recursive function?
  6. What happens if I forget the base case?
  7. Now it’s your turn!
  8. Recursion or a loop?

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.

Four Russian dolls in a row, from largest to smallest, with arrows for opening on the way in and for closing on the way back; the smallest one, which doesn’t open, is the base case
Opening a doll is like making one more call. The one that doesn’t open is the base case, and closing them all is the way back.

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:

StepCallWhat it does
1factorial(4)Waits for the result of factorial(3)
2factorial(3)Waits for the result of factorial(2)
3factorial(2)Waits for the result of factorial(1)
4factorial(1)Base case: returns 1
5factorial(2)Returns 2 × 1 = 2
6factorial(3)Returns 3 × 2 = 6
7factorial(4)Returns 4 × 6 = 24
The calls go down to the base case and are then resolved from back to front.

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.

Diagram of the calls of factorial(4) piling up down to the base case and being resolved on the way back
The calls of factorial(4): first they pile up, then they’re resolved from back to front.
See the animation of the call stack of factorial(4)
Animation of the call stack of factorial(4): the calls pile up until the base case and are then resolved from top to bottom, until the result 24
The same step by step in motion: the calls go up to the base case, and the answers come back down to the result.

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?

RecursionLoop
Good fit forProblems that split into equal, smaller parts, like folders inside foldersSimple repetitions, with a known start and end
MemoryUses the stack on every callUses less memory
ReadingUsually shorterMore straightforward for beginners
Differences between recursion and a loop.

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.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).