#include <stdio.h>
// Define a recursive function that calculates the factorial of a number
long long factorial(int n) {
if (n == 0) {
// Base case: the factorial of 0 is 1
return 1;
} else {
// Recursive case: the factorial of n is n * (n-1)!
return n * factorial(n - 1);
}
}
int main(void) {
// Call the factorial function and print the result
long long result = factorial(5);
printf("The factorial of 5 is %lld\n", result);
return 0;
}
This program defines a recursive function called factorial
that calculates the factorial of a number. It uses a recursive case to calculate the factorial of a number by calling itself with the input value decremented by 1, and a base case to handle the special case of the factorial of 0, which is defined to be 1.
Here is an example of the output of this program:
The factorial of 5 is 120
0 Comments