Example 1 — Factorial
n! = n * (n - 1)! with 0! = 1! = 1.
#include <stdio.h>
long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main(void) {
printf("0! = %ld\n", factorial(0));
printf("5! = %ld\n", factorial(5));
return 0;
} How It Works
factorial(5)becomes5 * factorial(4)and so on down tofactorial(1).- The base case returns
1, then each frame multiplies on the way back. - 5 * 4 * 3 * 2 * 1 = 120.
