DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

πŸͺ† Recursion Explained Like You're 5

Russian nesting dolls of code

Day 5 of 149

πŸ‘‰ Full deep-dive with code examples


The Nesting Dolls

Russian nesting dolls (Matryoshka):

  • Open the big doll
  • There's a smaller doll inside
  • Open that one
  • Another smaller doll inside
  • Keep going until the smallest one

Recursion is a function calling itself!


In Code

A function that calls itself to solve smaller pieces:

def countdown(n):
    if n == 0:
        print("Liftoff! πŸš€")
    else:
        print(n)
        countdown(n - 1)  # Calls itself!

countdown(3)
# Output: 3, 2, 1, Liftoff! πŸš€
Enter fullscreen mode Exit fullscreen mode

Each call handles a smaller problem (n-1) until we hit the base case (n=0).


The Two Rules

Every recursive function needs:

  1. Base Case β†’ When to stop (the smallest doll)
  2. Recursive Case β†’ Call itself with a smaller problem

Without a base case, it can behave like an infinite loop = πŸ’₯


Classic Example: Factorial

5! = 5 Γ— 4 Γ— 3 Γ— 2 Γ— 1

But also: 5! = 5 Γ— 4!

def factorial(n):
    if n == 1:           # Base case
        return 1
    else:
        return n * factorial(n-1)  # Recursive case
Enter fullscreen mode Exit fullscreen mode

In One Sentence

Recursion is solving a problem by breaking it into smaller versions of the same problem.


πŸ”— Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)