Learn how to write a C program to calculate the factorial of a number. This guide explains how to implement iterative methods for computing the factorial, including detailed examples and explanations. Ideal for beginners who want to understand fundamental concepts in C programming and factorial computation.
#include <stdio.h>
int main() {
int n, i;
unsigned long long factorial = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i) {
factorial *= i;
}
printf("Factorial of %d = %llu\n", n, factorial);
return 0;
}
Explanation:
Inside the main() function:
- An integer variable n is declared to store the input number.
- An unsigned long long variable factorial is initialized to 1 to store the factorial value.
- The user is prompted to enter a positive integer.
- A for loop is used to iterate from 1 to the entered number.
- Within the loop, each number is multiplied to the factorial variable.
- Finally, the factorial of the entered number is printed to the console.