Skip to content
Definition
Recursion is a programming technique where a function calls itself in order to solve a problem. This continues until a base condition is met, at which point the recursion halts and the stack unwinds.

Advantages and Disadvantages

Pros & Cons
Pros & Cons (Recursion):
AdvantagesDisadvantages
Simplifies code for naturally recursive problems (factorials, Fibonacci)Memory-intensive (each call adds a frame to the call stack)
Often results in more elegant, readable solutionsRisk of stack overflow with deep recursion
Fewer lines of code compared to iterative solutionsDebugging can be challenging
Direct translation of mathematical definitionsMay be slower than iteration due to function call overhead
Worked Example
Recursion Example: Factorial
pseudocode
function factorial(n):
    if n == 0 OR n == 1 then
        return 1
    end if
    return n * factorial(n - 1)
end function
CallExpansion
factorial(4)4 × factorial(3)
factorial(3)3 × factorial(2)
factorial(2)2 × factorial(1)
factorial(1)1 (base case)
Unwinding result: 2 × 1 = 2, 3 × 2 = 6, 4 × 6 = 24

Recursive vs Iterative:
pseudocode
// Recursive Fibonacci
function fibRecursive(n):
    if n <= 1 then
        return n
    end if
    return fibRecursive(n-1) + fibRecursive(n-2)
end function

// Iterative Fibonacci
function fibIterative(n):
    if n <= 1 then
        return n
    end if
    a = 0
    b = 1
    for i = 2 to n:
        temp = a + b
        a = b
        b = temp
    end for
    return b
end function

Recursion Compared with Iteration

Key Point
FeatureRecursionIteration
How it repeatsThe subroutine calls itself with a smaller version of the problemA loop repeats a block of code
How it stopsA base case returns a value without making another callThe loop condition is no longer met, or the count is reached
MemoryEvery call adds a frame to the call stack holding its parameters, local variables and return addressThe same variables are reused, so memory use does not grow
RiskStack overflow if the base case is never reached or the recursion is too deepAn infinite loop if the condition never changes
CodeOften shorter and closer to the way the problem is definedOften longer, but usually faster and easier to trace

Any algorithm written with recursion can be rewritten with iteration, and the other way round. When the last call reaches the base case, the calls return in reverse order as their frames are removed from the stack: this is the stack unwinding.