What are the different ways to implement factorial in the C language?
In the C language, factorial can be achieved through recursion and iteration.
- Recursively:
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n-1);
}
}
- Iterative approach:
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
Both methods can calculate the factorial of a given number, but the recursive method is relatively concise, while the iterative method is more memory efficient. The choice of method depends on specific requirements and application scenarios.