Open a Russian doll and you find a smaller doll inside. Open that one, and there is another, smaller still — until at last you reach a tiny doll that will not open. You have just performed a recursion: the same action repeated on a smaller version of itself, stopping only when you hit the one that cannot go further. In computing, a recursive function is a function that solves a problem by calling itself on a smaller piece of that problem.
Two parts every recursion needs
A recursive function always has two pieces. The base case is the simplest problem, which can be answered directly with no more calls — it is the tiny doll that will not open. The recursive case calls the function again on a smaller input, marching steadily towards the base case.
The call stack builds up, then unwinds
When a function calls itself, the computer pauses the outer call and remembers it on the call stack — like stacking plates. Calls pile up until the base case is met; then each call returns its answer and the stack unwinds back down, plate by plate.
Take factorial: 3! means 3×2×1 = 6. In recursion, fact(3) = 3 × fact(2), fact(2) = 2 × fact(1), fact(1) = 1 × fact(0), and fact(0) = 1 is the base case. As the stack unwinds, the multiplications finish: 1, then 2, then 6.
| Recursion | Iteration (loop) | |
|---|---|---|
| How it repeats | Function calls itself | A loop repeats a block |
| Stopping | Base case | Loop condition |
| Memory | Uses the call stack | Very little extra |
| Reads well for | Self-similar problems | Simple counting |
Memory hook: Every recursion needs a Base case to stop and a Recursive case that shrinks — "Base + smaller Self". No base case = infinite recursion = crash.