Implementation of factorial() Function
To implement a factorial()
function in C that calculates the factorial of a non-negative integer, you can create a recursive function. Here's an example of how to implement the factorial()
function:
Example:
#include <stdio.h>
// Function to calculate the factorial of a non-negative integer
unsigned long long factorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1
} else {
return n * factorial(n - 1); // Recursive case
}
}
int main() {
int number = 5;
unsigned long long result = factorial(number);
printf("Factorial of %d is %llu\n", number, result);
return 0;
}
In this example:
- The
factorial()
function takes an integer n
as its parameter and calculates the factorial recursively. The base case is when n
is 0, in which case the function returns 1. In the recursive case, it multiplies n
by the factorial of n - 1
.
- In the
main()
function, a number (5 in this case) is passed to the factorial()
function, and the result is stored in the result
variable.
- Finally, the program prints the result, showing the factorial of the input number.
Output:
Factorial of 5 is 120
You can use this factorial()
function to calculate the factorial of any non-negative integer by passing it as an argument to the function. Note that the result is of type unsigned long long
to handle larger factorials without overflowing.