Recursive Factorial in C

Level 4150 keystrokes

Implements factorial calculation using recursion with a base case.

C code

// Recursive factorial function
1long factorial(int n) {
// Base case: 0! and 1! equal 1
2 if (n <= 1) return 1;
// Recursive case: n! = n * (n-1)!
3 return n * factorial(n - 1);
4}
5
// Print factorial for 0 through 6
6for (int i = 0; i <= 6; i++) {
// Call factorial and print the result (%ld for a long)
7 printf("%d! = %ld\n", i, factorial(i));
8}

Output

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
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.

  • (× 6
  • )× 6
  • ;× 5
  • =× 4
  • ,× 2
  • "× 2
  • {× 2
  • }× 2
  • %× 2
  • +× 2

More C examples at level 4

← C typing practice