Write a C program to find the factorial of a number
Description: Take a number as input and print its factorial. Factorial of n is 1 x 2 x 3 x ... x n.
Hint:
- Start with
fact = 1and multiply it by each number from 1 to n. Useunsigned long longfor bigger values.
C program to find the factorial
#include <stdio.h>
int main(void) {
int n;
unsigned long long fact = 1;
printf("Enter a number: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
fact *= i;
}
printf("Factorial of %d = %llu\n", n, fact);
return 0;
}
Output:
Output of the above program is
Enter a number: 5
Factorial of 5 = 120
How it works
factbecomes 1, 2, 6, 24 and finally 120.- Factorial of 0 is 1, and our loop gives 1 for 0, so it is correct.
- The type
unsigned long longholds values up to 20! only.
Read C Recursion for the recursive way.
Learn more about the similar topics:
| Tutorials |
|---|
| C If Else Statement |
| C Else If Ladder and Nested If |
| C Switch Statement |
| C While Loop |
| C Do While Loop |
| C For Loop |
| C Nested Loops |