The factorial of a non-negative integer n is the product of all positive integers from 1 through n. By definition, 0! = 1.
n! = n × (n - 1) × ... × 2 × 1
#include <stdio.h>
int main(void) {
int number;
printf("Enter an integer from 0 to 20: ");
if (scanf("%d", &number) != 1 ||
number < 0 ||
number > 20) {
printf("Enter a value from 0 to 20.\n");
return 1;
}
unsigned long long factorial = 1;
for (int i = 2; i <= number; i++) {
factorial *= (unsigned long long)i;
}
printf("%d! = %llu\n", number, factorial);
return 0;
}
For input 10, the result is:
10! = 3628800
The upper limit of 20 prevents overflow when unsigned long long is 64 bits, because 21! no longer fits in 64 bits.
#include <stdio.h>
unsigned long long factorial_iterative(unsigned int number) {
unsigned long long result = 1;
for (unsigned int i = 2; i <= number; i++) {
result *= i;
}
return result;
}
int main(void) {
unsigned int number = 8;
printf("%u! = %llu\n",
number,
factorial_iterative(number));
return 0;
}
#include <stdio.h>
unsigned long long factorial_recursive(unsigned int number) {
if (number <= 1) {
return 1;
}
return number * factorial_recursive(number - 1);
}
int main(void) {
unsigned int number = 6;
printf("%u! = %llu\n",
number,
factorial_recursive(number));
return 0;
}
Recursion is useful for understanding function calls, but the loop version avoids recursive call overhead and is usually simpler for factorial.
Continue with factors of a number or review functions in C.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.