Recursion Explained With Simple Examples
SkillVeris Team
Engineering Team

Recursion is a technique where a function solves a problem by calling itself on a smaller version of the same problem until it reaches a simple base case.
In this guide, you'll learn:
- Every recursive function needs a base case that stops the recursion and a recursive case that moves closer to it, or it will run forever.
- Recursion shines for problems with self-similar structure, such as trees, nested data, and divide-and-conquer algorithms.
- Understanding the call stack explains both how recursion works and why deep recursion can run out of memory.
1What Is Recursion?
Recursion is a programming technique in which a function solves a problem by calling itself on a smaller version of that same problem. Instead of looping, the function breaks the task into a slightly simpler subtask, hands that subtask to another copy of itself, and combines the result. This continues until the subtask is so simple it can be answered directly.
The idea can feel circular at first, but it mirrors how we solve many problems in real life. To search a stack of boxes, you open one box; if it contains more boxes, you apply the same search to each of those, and so on, until you reach boxes with no boxes inside. That repeated application of the same procedure to smaller pieces is the essence of recursion.
Recursion is not a niche trick. It is a fundamental way of thinking that makes certain problems dramatically simpler to express than loops would, especially problems whose structure repeats itself at smaller scales.
2The Base Case and the Recursive Case
Every correct recursive function has two essential parts. The first is the base case, a condition simple enough to answer immediately without any further recursion. The base case is what stops the process; without it, the function would call itself endlessly.
The second is the recursive case, where the function does a little bit of work and then calls itself on a smaller input that moves closer to the base case. The key requirement is progress: each recursive call must shrink the problem so that it eventually reaches the base case rather than spinning forever.
You can think of these two parts as a promise and a step. The base case promises the recursion will end, and the recursive case takes one step toward that ending. Get either part wrong and the whole thing breaks, so checking both is the first thing to do when writing or debugging recursive code.
3A First Example: Counting Down
Imagine a function that counts down from a number to zero. The base case is when the number reaches zero: at that point there is nothing left to do, so the function simply stops. The recursive case handles any positive number by announcing it and then calling itself with the number reduced by one.
Trace it by hand starting at three. The function announces three, then calls itself with two, which announces two and calls itself with one, which announces one and calls itself with zero. At zero the base case triggers and the chain unwinds. Each call did a tiny piece of the work and delegated the rest.
This simple example captures the whole pattern. There is a stopping condition, a small action, and a call on a smaller input. Almost every recursive function you will ever write follows this same shape, no matter how complex the problem looks.
4The Classic Factorial
The factorial of a number is the product of all whole numbers from one up to that number, and it is the textbook example of recursion because its definition is already recursive. The factorial of a number equals that number multiplied by the factorial of the number just below it.
The base case is the factorial of zero or one, which is simply one. The recursive case takes any larger number, multiplies it by the factorial of the number one smaller, and returns the result. The definition and the code look almost identical, which is part of what makes recursion elegant.
This example shows recursion's strength: when a problem is naturally defined in terms of a smaller version of itself, the recursive solution reads almost like the mathematical definition. The code becomes a direct translation of the idea rather than a mechanical loop.
5How the Call Stack Works
To understand what happens under the hood, you need the call stack. Every time a function is called, the computer sets aside a small region of memory, called a stack frame, to hold that call's local information. When the function returns, its frame is discarded and control goes back to whoever called it.
With recursion, each self-call adds a new frame on top of the stack before any of them finish. The frames pile up as the recursion goes deeper, and only when the base case is reached do they begin to return and unwind, one at a time, from the top down. This is why the earlier count-down example unwinds in reverse.
Seeing the stack in your mind is the single most helpful skill for reasoning about recursion. It explains the order in which work happens, why values combine the way they do, and what goes wrong when recursion misbehaves.
6Infinite Recursion and Stack Overflow
If a recursive function never reaches its base case, it keeps calling itself and keeps adding frames to the stack. Because the stack has a limited size, it eventually fills up completely and the program crashes with an error commonly known as a stack overflow.
The usual causes are a missing base case, a base case that can never be reached, or a recursive call that fails to shrink the problem. Each of these breaks the promise that the recursion will end. When your recursive code crashes, these are the first suspects to check.
This is also why very deep recursion can be risky even when it is technically correct. A problem that recurses many thousands of levels deep may exhaust the stack simply because each level consumes a frame, regardless of whether the logic is sound.
7Recursion Versus Iteration
Anything you can do with recursion you can also do with a loop, and vice versa, so the choice is often about clarity rather than capability. For simple repetition, a loop is usually clearer and avoids the overhead of many function calls. For problems with nested or self-similar structure, recursion is often far more natural and readable.
Loops also avoid the stack-depth limit, since they do not pile up frames. This makes iteration the safer choice when a problem could recurse extremely deep. Recursion, by contrast, trades a little performance and stack space for expressive power on the right kinds of problems.
The mature view is that neither is universally better. Reach for recursion when it makes the solution obviously simpler and the depth stays reasonable, and reach for a loop when plain repetition is all you need.
8Where Recursion Shines
Recursion is at its best on problems whose structure repeats at smaller scales. Trees are the prime example: to process a tree, you process its root and then recursively process each of its subtrees, which are themselves smaller trees. The recursive shape matches the data's shape perfectly.
Nested data of any kind fits the same pattern. Walking a folder that contains files and other folders, exploring a menu with submenus, or parsing an expression with parentheses inside parentheses all become clean when each level of nesting is handled by a recursive call.
Divide-and-conquer algorithms are another natural home. These break a problem into smaller independent pieces, solve each piece recursively, and combine the results. Many efficient sorting and searching strategies are built on exactly this recursive idea.
9The Divide-and-Conquer Idea
Divide and conquer is a powerful recursive strategy with three steps: divide the problem into smaller subproblems, conquer each subproblem by solving it recursively, and combine the subresults into the final answer. When the subproblems are much smaller than the original, this approach can be remarkably efficient.
A familiar illustration is searching a sorted list by repeatedly cutting the search range in half. Each step discards half of the remaining possibilities, so even a huge list is narrowed down in a small number of steps. The recursion naturally expresses this halving.
Recognizing when a problem can be split into independent smaller versions of itself is a valuable skill. Once you see that structure, recursion turns a daunting task into a short, clear solution built from simple pieces.
10Common Pitfalls to Avoid
The most common pitfall is forgetting or misplacing the base case, which leads straight to infinite recursion. Whenever you write a recursive function, define the base case first and confirm that every recursive path eventually reaches it.
Another pitfall is recomputing the same subproblem many times. Some naive recursive solutions solve identical smaller problems over and over, wasting enormous effort. Techniques such as remembering previously computed results can fix this and turn a slow recursion into a fast one.
A third pitfall is unnecessary recursion on problems that a simple loop would handle more clearly. Recursion is a tool, not a badge of sophistication, and using it where it adds no clarity only makes code harder to follow and more fragile.
11Building the Right Intuition
The mental leap that makes recursion click is trusting that the recursive call already works. When you write the recursive case, assume the function correctly solves the smaller problem, and focus only on how to combine that smaller result with the current step. This leap of faith is what lets you reason about recursion without tracing every level by hand.
It helps to think in terms of the smallest case and one step. Ask what the simplest input looks like, which becomes your base case, and how a larger input relates to a slightly smaller one, which becomes your recursive case. If both answers are clear, the function almost writes itself.
With practice, this way of thinking becomes second nature, and problems that once looked intimidating reveal a simple repeating structure underneath.
A useful habit is to name the smaller problem out loud before writing any code. If you can describe what the recursive call returns in a single sentence, you can usually combine its result with the current step in one more line. Struggling to state that sentence is often a sign the problem needs to be broken down differently.
12Helpers and Accumulators
Sometimes a recursive function needs to carry extra information along as it descends, such as a running total or the position it has reached. A common technique is to introduce a helper function that takes an additional parameter, often called an accumulator, which holds the partial result built up so far.
The accumulator lets each recursive call pass its progress forward instead of waiting to combine everything on the way back up. This can make some recursive solutions clearer and, in certain languages and situations, more efficient because the intermediate result travels down with the call.
You do not need accumulators for every recursive function, but recognizing when a small helper with an extra parameter simplifies the logic is a valuable step in maturing from basic recursion to fluent, confident use of the technique.
13Practice Recursion on SkillVeris
Recursion is learned through repetition and tracing. Start by writing tiny recursive functions, like counting down or summing a list, and trace each call on paper to watch the stack grow and unwind. Then move on to tree and nested-data problems where recursion truly shines.
On SkillVeris, guided lessons and exercises take you from your first base case to divide-and-conquer thinking, with step-by-step walkthroughs of the call stack. Working through progressively harder recursive problems is the surest way to develop the intuition that turns recursion from confusing to obvious.
Get The Print Version
Download a PDF of this article for offline reading.
About the Publisher
SkillVeris Team
Engineering Team
Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.
View all postsRelated Posts
Never miss an update
Get the latest tutorials and guides delivered to your inbox.
No spam. Unsubscribe anytime.