Certainly! Here is a simple algorithm to calculate the factorial of a non-negative integer in C language using both iterative and recursive methods:
Iterative Method:
The iterative approach uses a loop to calculate the factorial.
#include <stdio.h>
// Function to calculate factorial iteratively
unsigned long long factorial_iterative(int n) {
unsigned long long result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
int main() {
int number;
printf("Enter a non-negative integer: ");
scanf("%d", &number);
if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d: %llu\n", number, factorial_iterative(number));
}
return 0;
}
Recursive Method:
The recursive approach calls the function itself with a decremented value until it reaches the base case (n == 0 or n == 1).
#include <stdio.h>
// Function to calculate factorial recursively
unsigned long long factorial_recursive(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial_recursive(n - 1);
}
}
int main() {
int number;
printf("Enter a non-negative integer: ");
scanf("%d", &number);
if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d: %llu\n", number, factorial_recursive(number));
}
return 0;
}
Explanation:
Iterative Method:
The function factorial_iterative initializes result to 1.
It then multiplies result by every integer from 1 to n.
This is accomplished using a for loop.
The final value of result is returned as the factorial of n.
Recursive Method:
The function factorial_recursive uses a base case: if n is 0 or 1, it returns 1.
For values greater than 1, it calls itself with n-1 and multiplies the result with n.
This continues until the base case is met.
In both cases, main function handles the input and output, and performs a check to ensure the input is a non-negative integer. If the input is negative, an appropriate message is displayed.
Feel free to use either the iterative or recursive method depending on your preference or requirements. The iterative method may be more efficient for larger numbers since recursion could lead to stack overflow errors for very large values of n.