Recursive Function in C

Level 5110 keystrokes

Defines a recursive factorial function: n! is n times (n - 1)!, and the recursion stops at n <= 1, where it returns 1. factorial(5) prints 120.

C code

// Computes n! by calling itself with smaller values
1int factorial(int n) {
// Base case: 0! and 1! are 1, so the recursion stops here
2 if (n <= 1) {
3 return 1;
4 }
// Recursive case: n! = n * (n - 1)!
5 return n * factorial(n - 1);
6}
7
// 5! = 5 * 4 * 3 * 2 * 1, so this prints 120
8printf("%d\n", factorial(5));

Output

120
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • (× 5
  • )× 5
  • ;× 3
  • "× 2
  • {× 2
  • }× 2
  • -× 1
  • ,× 1
  • *× 1
  • \× 1

More C examples at level 5

← C typing practice