How Recursion Works?

Recursion is when a problem solves itself by breaking into smaller, similar pieces, like stacking blocks one on top of another.

Imagine you have a tower of blocks, and you want to count how many there are. You start with the top block. Then you ask your friend to count the rest of the tower below it. Your friend does the same: they take the top block of their tower, then asks their friend to count what’s left. This keeps going until someone gets to the bottom, and then all the counts come back up like a chain.

Like a Russian Nesting Doll

Think of recursion like opening a Russian nesting doll (matryoshka). You open one, find another smaller doll inside, and keep opening them one by one. Eventually, you get to the tiniest doll, and then you start closing them again, counting how many there were.

Each time the problem gets smaller, it's like taking off a layer of the doll. When the smallest part is solved, the bigger parts know what to do next, just like when you finish the last block, everyone else knows how many blocks they counted too!

Take the quiz →

Examples

  1. A recursive function is like a Russian nesting doll, each layer calls the next, until it reaches the smallest one.

Ask a question

See also

Discussion

Recent activity