MyLeoNes™

Recursion: solving a problem with smaller versions of itself — Technology, 14–17 years

Recursion is a way to make a program repeat an idea by calling itself on a smaller case. It must also know when to stop, or the process never ends.

A smaller copy of the same problem

Imagine opening a set of nested boxes: inside each box is another, smaller box, until the last one is empty. A recursive program does something similar, solving a smaller version of its task each time. It needs a base case that gives a direct answer.

Why use recursion?

Some problems already have a branching or nested shape: folders contain folders, web pages link to pages, and family trees split into smaller branches. Recursion matches that shape, so the code can be clearer than a long list of special cases.

Worked example: factorial

To calculate 4!, define 1! as 1, then use n! = n × (n−1)!. So 4! becomes 4 × 3!, then 4 × 3 × 2!, then 4 × 3 × 2 × 1!, giving 24. The base case 1! stops the chain.

The missing stopping point

A common mistake is writing the self-call but forgetting the base case, or changing the input so little that it never reaches it. This is reasonable because the repeating step looks like the main idea. The result is usually a stack overflow: too many unfinished calls.

Where it appears

File explorers can search through folders inside folders, and drawing software can create branching shapes such as trees or snowflakes. These tasks have nested structure, so recursion can describe them naturally. It is not always fastest; an iterative method may use less memory.

Keep exploring

Other languages

Loading MyLeoNes™…