๐Ÿ”€โšก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>
2
3int 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 input
11 if (n < 0) {
12 printf("Factorial not defined for negative numbers\n");
13 return 1;
14 }
15
16 // Calculate factorial using loop
17 for (int i = 1; i <= n; i++) {
18 fact *= i; // fact = fact * i
19 }
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,600
13! = 6,227,020,800
20! = 2.4 ร— 10ยนโธ
int max = ~2 billion

unsigned 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