Lesson 32 of 50 intermediate

Recursion — The Magic of Self-Calling Functions

When a function calls itself — and it actually works!

Open interactive version (quiz + challenge)

Real-world analogy

Recursion is like Russian nesting dolls — you open one doll and find a smaller one inside. You keep opening until you find the tiniest doll (the base case). Then you close them all back up. Each doll is a function call, and the smallest doll tells you when to stop!

What is it?

Recursion is a technique where a function solves a problem by calling itself with a smaller version of the same problem. Every recursive function needs a base case (when to stop) and a recursive case (how to make the problem smaller). It's like solving a big puzzle by breaking it into identical smaller puzzles.

Real-world relevance

Recursion appears everywhere! File systems use recursion (folders inside folders inside folders). Google's search algorithm uses recursion to crawl web pages. Family trees are recursive (you have parents, who have parents, who have parents...). Even Russian nesting dolls and fractal art are recursive patterns!

Key points

Code example

#include <bits/stdc++.h>
using namespace std;

// Factorial using recursion
int factorial(int n) {
    if (n <= 1) return 1;  // Base case!
    return n * factorial(n - 1);  // Recursive case
}

// Sum from 1 to n using recursion
int sumTo(int n) {
    if (n == 1) return 1;  // Base case
    return n + sumTo(n - 1);  // Recursive case
}

int main() {
    cout << "5! = " << factorial(5) << "\n";  // 120
    cout << "Sum 1 to 10 = " << sumTo(10) << "\n";  // 55
    
    // Let's trace factorial(4):
    // factorial(4) = 4 * factorial(3)
    //              = 4 * 3 * factorial(2)
    //              = 4 * 3 * 2 * factorial(1)
    //              = 4 * 3 * 2 * 1
    //              = 24
    cout << "4! = " << factorial(4) << "\n";  // 24
    return 0;
}

Line-by-line walkthrough

  1. 1. #include — includes all standard libraries so we can use cout, cin, and everything else we need.
  2. 2. using namespace std; — lets us write cout instead of std::cout.
  3. 3. int factorial(int n) — we define a function that takes a number n and returns its factorial. The return type is int.
  4. 4. if (n <= 1) return 1; — this is the BASE CASE! When n is 0 or 1, we know the factorial is 1, so we return immediately without making another recursive call. This is what stops the recursion.
  5. 5. return n * factorial(n - 1); — this is the RECURSIVE CASE. We multiply n by the factorial of (n-1). We trust that factorial(n-1) will give us the correct answer for the smaller problem.
  6. 6. int sumTo(int n) — another recursive function that adds all numbers from 1 to n.
  7. 7. if (n == 1) return 1; — base case for the sum function. The sum from 1 to 1 is just 1.
  8. 8. return n + sumTo(n - 1); — recursive case: n plus the sum of all numbers from 1 to (n-1).
  9. 9. In main(), we call factorial(5) which returns 120 (5×4×3×2×1) and sumTo(10) which returns 55 (1+2+3+...+10).

Spot the bug

#include <bits/stdc++.h>
using namespace std;

int factorial(int n) {
    return n * factorial(n - 1);
}

int main() {
    cout << factorial(5) << "\n";
    return 0;
}
Need a hint?
What happens when factorial keeps calling itself? Is there anything that tells it when to stop?
Show answer
The bug is a MISSING BASE CASE! The function calls factorial(5), then factorial(4), then factorial(3), factorial(2), factorial(1), factorial(0), factorial(-1)... and it never stops! This causes a stack overflow crash. The fix is to add 'if (n <= 1) return 1;' at the beginning of the function before the recursive call.

Explain like I'm 5

Imagine you're in a line of people, and you want to know how many people are in the line. You ask the person behind you: 'How many people are behind you?' They ask the person behind THEM the same question. This keeps going until the last person says 'Zero — nobody is behind me!' (that's the base case). Then each person adds 1 and passes the answer forward. That's recursion — asking the same question to a smaller group!

Fun fact

The word 'recursion' is itself recursive in a fun way — if you Google 'recursion', Google shows 'Did you mean: recursion?' as a joke! Also, the famous computer scientist Niklaus Wirth once said: 'To understand recursion, you must first understand recursion.' 🤯

Hands-on challenge

Write a recursive function called power(base, exp) that calculates base^exp. For example, power(2, 3) should return 8. The base case is: any number to the power of 0 is 1. The recursive case is: power(base, exp) = base * power(base, exp - 1). Test it with power(3, 4) — it should give 81!

More resources

Open interactive version (quiz + challenge) ← Back to course: CP Zero to Hero