0Pricing
C Academy · Lesson

Recursion vs Iteration

When to choose each.

Two Ways To Repeat

Many problems can be solved with either recursion or iteration. Iteration uses loops; recursion uses function calls.

Both can produce the same result, but they differ in style, memory use, and speed.

Factorial With A Loop

Here is factorial written iteratively with a for loop. No function calls itself; a single variable accumulates the product.

#include <stdio.h>

long factorial(int n) {
    long result = 1;
    for (int i = 2; i <= n; i++)
        result *= i;
    return result;
}

int main(void) {
    printf("%ld\n", factorial(6));
    return 0;
}

All lessons in this course

  1. How Recursion Works
  2. Classic Recursive Problems
  3. Recursion vs Iteration
  4. Avoiding Stack Overflow
← Back to C Academy