๐โกBeginner
Find Factorial of a Number
Calculate n! using loop
Factorial of n (written as n!) is the product of all positive integers from 1 to n.n! = n ร (n-1) ร (n-2) ร ... ร 2 ร 1
Special case: 0! = 1
๐ Factorial Examples
0!
= 1
5!
= 120
5ร4ร3ร2ร1
7!
= 5040
10!
= 3628800
C Program to Find Factorial
factorial.c
C
1#include <stdio.h>23int main() {4 int n;5 unsigned long long fact = 1; // Use large type!6 7 printf("Enter a number: ");8 scanf("%d", &n);9 10 // Check for negative input11 if (n < 0) {12 printf("Factorial not defined for negative numbers\n");13 return 1;14 }15 16 // Calculate factorial using loop17 for (int i = 1; i <= n; i++) {18 fact *= i; // fact = fact * i19 }20 21 printf("%d! = %llu\n", n, fact);22 23 return 0;24}Output
Enter a number: 5
5! = 120
Calculation Process for 5!
Step-by-Step Execution:
1
Initialize
fact = 1
2
i = 1
fact = 1 ร 1 = 1
3
i = 2
fact = 1 ร 2 = 2
4
i = 3
fact = 2 ร 3 = 6
5
i = 4
fact = 6 ร 4 = 24
6
i = 5
fact = 24 ร 5 = 120
7
Output
5! = 120
โ ๏ธ Why Use unsigned long long?
Factorials grow VERY fast:
12! = 479,001,60013! = 6,227,020,80020! = 2.4 ร 10ยนโธint max = ~2 billionunsigned long long can store values up to ~18 ร 10ยนโธ
๐ Key Takeaways
โn! = n ร (n-1) ร ... ร 1
โ0! = 1 (by definition)
โUse
unsigned long long for large valuesโFactorial not defined for negatives
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials