Recursive function in C++

Level 3106 keystrokes

factorial calls itself with n - 1 until it reaches the base case n <= 1, so factorial(5) = 5 × 4 × 3 × 2 × 1 = 120.

C++ code

1int factorial(int n) {
// Base case: stops the recursion (0! and 1! are 1)
2 if (n <= 1) return 1;
// Recursive case: n! = n × (n - 1)!
3 return n * factorial(n - 1);
4}
5
// 5 × 4 × 3 × 2 × 1: prints 120
6cout << factorial(5) << endl;

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
  • (× 4
  • )× 4
  • ;× 3
  • -× 1
  • {× 1
  • }× 1
  • *× 1
  • =× 1

More C++ examples at level 3

← C++ typing practice