How to represent the factorial function in the C programming language?
In the C language, factorial functions can be implemented using either recursion or loops.
- Implementing the factorial function recursively.
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n-1);
}
}
- Implement factorial function using recursion.
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
Both methods can achieve the factorial function, just implemented in different ways. The recursive method calculates the factorial by repeatedly calling itself, while the iterative method calculates the factorial through looping iterations.