Recursive Function in C

Level 5175 keystrokes

Defines a recursive factorial function that calls itself with n - 1 until it reaches the base case n <= 1. main prints 5! = 120 and 7! = 5040.

C code

// Computes n! (n factorial) recursively
1int factorial(int n) {
// Base case: 0! and 1! are both 1
2 if (n <= 1) {
// Returning without another call stops the recursion
3 return 1;
4 }
// Recursive case: n! = n * (n - 1)!, so the function calls itself with a smaller n
5 return n * factorial(n - 1);
6}
7
// Program entry point
8int main() {
// 5! = 5 * 4 * 3 * 2 * 1, so this prints 5! = 120
9 printf("5! = %d\n", factorial(5));
// 7! = 7 * 6 * 120, so this prints 7! = 5040
10 printf("7! = %d\n", factorial(7));
// Returns 0 to report that the program ended normally
11 return 0;
12}

Output

5! = 120
7! = 5040
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.

  • (× 8
  • )× 8
  • ;× 5
  • "× 4
  • {× 3
  • }× 3
  • =× 3
  • ,× 2
  • !× 2
  • \× 2

More C examples at level 5

← C typing practice