Skip to main content

Recursion versus iteration

Short answer

Recursion divides the problem via self-calls with a base case, using extra stack memory and being slower. Iteration repeats statements with loops, using constant memory and executing faster. Both yield the same results.

How is recursion different from iteration?

Recursion solves a problem by a function calling itself on smaller inputs, whereas iteration repeats a block of statements using loops (for, while). Recursion uses more memory (a stack frame per call) and is usually slower, but is shorter for naturally recursive problems; iteration uses less memory and is faster. Both compute the same results:

#include <stdio.h>
int sum_rec(int n) { return n == 0 ? 0 : n + sum_rec(n - 1); }
int sum_iter(int n)
{
    int i, s = 0;
    for (i = 1; i <= n; i++)
        s += i;
    return s;
}
int main(void)
{
    printf("%d %d\n", sum_rec(5), sum_iter(5));
    return 0;
}

Output:

15 15

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 6 questions →