📘 CodingMarble Learn

Recursion: Functions That Call Themselves

Recursion is when a function solves a problem by calling itself on a smaller version of the same problem. Every recursive function needs a base case, where it stops and returns an answer directly, and a recursive case that moves closer to the base case. Each call gets its own stack frame on the call stack; frames are removed as calls return.

🎬 Step-by-step story

  1. fact(4) means 4 × 3 × 2 × 1. Look inside: fact(4) is just 4 × fact(3). And fact(3) is 3 × fact(2). Each box holds a smaller copy of the same problem.
  2. The smallest box is fact(1). Its answer is simply 1. This is the base case. Here the function stops calling itself.
  3. When the program runs, each call puts a new frame on the call stack. The tower grows: fact(4), fact(3), fact(2), fact(1).
  4. Now the answers come back down. fact(1) returns 1. Then 2 × 1 = 2, 3 × 2 = 6, 4 × 6 = 24. Each frame leaves the stack when it returns.
  5. What if there is no base case? The calls never stop. Frames pile up until memory runs out. This error is a stack overflow.
  6. Your turn. Pick a number n and press play. Watch the frames go up, then come back down with the answers.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

How can a function call itself before it is finished?

Each call is a separate copy with its own n. fact(4) pauses at the line fact(3) and a new copy starts. See the nested boxes in step 1.

Why do we need a base case?

It is the one input small enough to answer without calling again. Without it the calls go on forever. Step 2 lights up the base-case box.

Where is n = 4 kept while fact(3) runs?

In fact(4)'s own stack frame, which waits on the stack. Every frame keeps its own n. See the tower in step 3.

When does the multiplication actually happen?

On the way back down. fact(4) can only multiply 4 × fact(3) after fact(3) has returned 6. Step 4 shows each product as frames pop.

What is a stack overflow?

The stack has limited memory. If calls never reach a base case, frames keep piling up until there is no room and the program crashes. Watch step 5.

Is recursion slower than a loop?

Often a little, because each call adds a frame. For fact(n) the stack gets n frames tall; press play with n = 7 in free play to see it. A loop uses one frame.

What is recursion?

A function is a named block of code that does one job. Usually it calls other functions.

A recursive function calls itself. It solves a big problem by first solving a smaller copy of the same problem.

Example: the factorial n! = n × (n − 1) × … × 1. Notice that 5! = 5 × 4!. So to find fact(5), find fact(4) and multiply by 5.

def fact(n):
    if n == 1:          # base case
        return 1
    return n * fact(n - 1)   # recursive case

Base case and recursive case

Every correct recursive function has two parts:

If either part is wrong, the function never stops. For example fact(n − 1) with no base case, or fact(n + 1) that moves away from it.

The call stack and stack frames

The computer keeps track of unfinished calls using the call stack. A stack works like a pile of plates: last in, first out.

Each call gets a stack frame. The frame stores its own parameters (like n), its local variables and the return address (where to continue after it finishes).

  1. fact(4) starts and waits for fact(3). Its frame stays on the stack.
  2. fact(3) waits for fact(2), which waits for fact(1).
  3. fact(1) hits the base case and returns 1. Its frame is popped.
  4. Each waiting frame now finishes its multiplication and is popped in turn.

Too many frames fill the stack's memory. The program crashes with a stack overflow (Python says RecursionError).

Tracing a recursive function

To trace, write each call on a new line, indented one level deeper. When a call returns, write its value and go back up.

power(2, 3)
  power(2, 2)
    power(2, 1)
      power(2, 0) returns 1
    returns 2 × 1 = 2
  returns 2 × 2 = 4
returns 2 × 4 = 8

A function that calls itself twice, like Fibonacci fib(n) = fib(n − 1) + fib(n − 2), makes a tree of calls. fib(5) calls fib(3) twice and fib(2) three times, so plain recursion repeats a lot of work. Storing answers you already found (memoisation) fixes this.

Recursive searching and sorting

Binary search on a sorted list: look at the middle item. If it is the target, stop (base case). If the target is smaller, search the left half; if bigger, the right half. An empty range is the other base case (not found). Each call halves the list, so a list of 1 000 items needs about 10 calls.

Merge sort: a list of 0 or 1 items is already sorted (base case). Otherwise split it in two halves, sort each half recursively, then merge the two sorted halves. This "divide and conquer" idea is behind many fast algorithms.

Recursion or a loop?

Anything done with recursion can also be done with a loop (iteration), and the reverse is also true.

Some languages (functional languages) use recursion as the main way to repeat.

Try it: the queue in class

Ask the last student in a line: "How many people are in front of you?" They do not count. They ask the person in front the same question and add 1 to the answer. The first person in line has no one in front and says 0 (the base case). The answers travel back down the line. Then write fact(n) or count(n) in Python and run it with n = 5. Compare with step 4 of the 3D.

Key formulas and definitions

Worked examples

1. Write a recursive function to add the numbers 1 to n.

Base case: n = 0 → return 0. Recursive case: return n + total(n − 1). <pre>def total(n): if n == 0: return 0 return n + total(n - 1)</pre>total(4) = 4 + 3 + 2 + 1 + 0 = 10.

2. Trace fact(3) and show the stack.

Calls: fact(3) → fact(2) → fact(1). Stack at its tallest: fact(1) on top of fact(2) on top of fact(3). Returns: fact(1) = 1, fact(2) = 2 × 1 = 2, fact(3) = 3 × 2 = 6.

3. What is wrong with: def f(n): return n * f(n - 1)

There is no base case. f(3) calls f(2), f(1), f(0), f(−1)… forever. Python stops it with RecursionError (stack overflow). Add: if n <= 1: return 1.

4. Write a recursive function that reverses a string.

Base case: empty string returns itself. Otherwise take the last character plus the reverse of the rest. <pre>def rev(s): if s == "": return "" return s[-1] + rev(s[:-1])</pre>rev("cat") = "t" + rev("ca") = "t" + "a" + rev("c") = "tac".

5. How many calls does fib(4) make in total (plain recursion)?

fib(4) → fib(3), fib(2). fib(3) → fib(2), fib(1). Each fib(2) → fib(1), fib(0). Count: fib(4) 1, fib(3) 1, fib(2) 2, fib(1) 3, fib(0) 2 = 9 calls.

6. Binary search for 23 in [3, 8, 15, 23, 42, 57, 61]. Show each call.

Call 1: middle is 23 at index 3. Found in 1 call. Search for 57: call 1 middle 23 < 57 → right half [42, 57, 61]; call 2 middle 57 → found. 2 calls.

Common mistakes

Practice quiz

1. A recursive function is one that:
2. The part of a recursive function that stops the calls is the:
3. Each function call is stored on the call stack as a:
4. fact(5) using fact(n) = n × fact(n − 1), fact(1) = 1, equals:
5. Recursion with no base case usually ends with a:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is recursion in simple words?

Recursion is when a function solves a problem by calling itself on a smaller version of the same problem, until it reaches a case simple enough to answer directly.

What is a base case in recursion?

It is the stopping condition: the simplest input, whose answer the function returns without calling itself again.

Is recursion better than iteration?

Neither is always better. Recursion is clearer for nested problems like trees and merge sort; loops use less memory and cannot overflow the stack.

Where this is taught

RomaniaClasa a XI-aSubprograms
Ukraine10 класProgramming language and data structures
England (GCSE, A level)Year 134.1 Fundamentals of programming (A-level)
USA (Common Core, NGSS, AP)Grade 11Data Collections
USA (Common Core, NGSS, AP)Grade 11Algorithms and Programming
Germany (Bavaria)Jahrgangsstufe 12Recursion
FranceTerminaleLanguages and programming
Russia9 классAlgorithms and programming

Learn first

Learn next

Related lessons

All Computer Science lessons