Programming

What is recursion in programming?

Short answer

Recursion is when a function calls itself to solve a smaller version of the same problem, until it reaches a base case simple enough to answer directly.

A recursive function has two essential parts: a base case (a simple condition where the function returns a direct answer, without calling itself again), and a recursive case (where it calls itself with a smaller or simpler input, moving toward the base case).

A classic example: factorial

Factorial of n (written n!) is n × (n-1) × (n-2) × ... × 1. Recursively: factorial(n) = n × factorial(n-1), with the base case factorial(0) = 1. Calling factorial(4) triggers factorial(3), which triggers factorial(2), and so on, until it hits the base case and the results multiply back up the chain.

When recursion helps

Recursion is a natural fit for problems that are inherently self-similar, like traversing tree structures, searching nested folders, or certain sorting algorithms (like quicksort and mergesort). Without a correct base case, though, a recursive function will call itself forever and crash with a stack overflow error.

Last reviewed: September 2026