C Workshop · Recursive Factorial
Lesson C

Recursive Factorial

A function may call itself. Factorial is n * fact(n-1), and fact(1) is 1 so the chain stops.

What it is

Factorial n! means n × (n-1) × … × 1, and 1! (and 0!) is 1. A recursive function asks a smaller clone of itself for help, then multiplies. fact(4) is 24.

Approach

  1. Base: if n <= 1 return 1.
  2. Recursive step: return n * fact(n - 1).
  3. Print fact(4).

Where this is used in the real world

Diagram

1

fact(4)

4*fact(3)

2

fact(3)

3*fact(2)

3

fact(1)

1

4

24

unwind

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int fact(int n) {
3    if (n <= 1) return 1;
4    return n * fact(n - 1);
5}
6int main(void) {
7    printf("%d\n", fact(4));
8    return 0;
9}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. fact(4) is:

4*3*2*1.

2. The base case is:

Stops recursion.

3. Without a base case:

Must stop.

4. An iterative kind of factorial uses:

Same result, no stack growth.

5. fact(1) returns 1 so that:

Bottom of the chain.