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) recursively1int factorial(int n) { // Base case: 0! and 1! are both 12 if (n <= 1) { // Returning without another call stops the recursion3 return 1;4 } // Recursive case: n! = n * (n - 1)!, so the function calls itself with a smaller n5 return n * factorial(n - 1);6}7 // Program entry point8int main() { // 5! = 5 * 4 * 3 * 2 * 1, so this prints 5! = 1209 printf("5! = %d\n", factorial(5)); // 7! = 7 * 6 * 120, so this prints 7! = 504010 printf("7! = %d\n", factorial(7)); // Returns 0 to report that the program ended normally11 return 0;12}Output
5! = 120 7! = 5040
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