Skip to content
BENIBIX Learn

Base Case

Development🧮 Algorithms & Data StructuresAlgorithm Design Techniques

Also known as Base Case (Recursion), Stopping Condition, Terminating Case

The simple case where a function that calls itself stops.

Think of it like

It is like the bottom step of a staircase. Once you reach it, you stop going down.

Example

A countdown function prints n, then calls itself with n minus 1. When n is 0, the base case prints Go! and stops.

Why it matters

It is what makes recursion end. Every recursive function needs one that the input is sure to reach.

Definition

A base case is the simplest input a recursive function answers at once, without calling itself again. Every other call makes the problem a bit smaller, until it reaches the base case. Then the answers pass back up. Without a base case, the calls never stop. The program runs out of stack space and crashes.

Example code

python
def countdown(n):
    if n == 0:        # base case
        print("Go!")
        return
    print(n)
    countdown(n - 1)

countdown(3)  # 3 2 1 Go!
When n reaches 0, the function stops calling itself.
On the left, the calls count down to 0. The base case stops them.

Common mistake

Writing a base case the input can skip past, like n == 0 when n goes down by 2 from 5. The calls never stop.

Key takeaways

  1. 1
    Answer at once. No more self-calls.
  2. 2
    Must be reached. Each call moves toward it.
  3. 3
    Stops the stack. Without it, the program crashes.

Learn it properly