basics · beginner · ~15 min

Factorial

Use a loop to accumulate a product.

Challenge

Implement unsigned long factorial(int n) for n >= 0. factorial(0) == 1. You may assume the result fits in unsigned long.

Why this matters

Factorial is the simplest non-trivial recursive-or-iterative function. It also overflows fast — 13! overflows int — making it a great teaching example for integer-size choice.

Starter code

unsigned long factorial(int n) {
    /* TODO */
    return 0;
}

Common mistakes

Returning int (overflows at 13!). Forgetting the 0! = 1 base case. Iterating from 0 instead of 1 (multiplies by 0).

Edge cases to handle

0! must be 1 (by convention). Large n overflows unsigned long long at 21!.

Complexity

O(n) iterative, O(n) stack depth recursive.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.