OverIQ.com

C Program to find the factorial of a number

Last updated on July 27, 2020


The following C program find the factorial of a number:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*******************************************************
 * Program to find the factorial of a number
********************************************************/

#include <stdio.h>

int main() 
{
    int n, i;
    unsigned long int fact = 1;

    printf("Enter a number: ");
    scanf("%d", &n);

    for(i = n; i > 0; i--)
    {        
        fact = fact * i;                
    }

    printf("%d! = %d", n, fact);

    return 0;
}

Expected Output 1st run:

1
2
Enter a number: 5
5! = 120

2nd run:

1
2
Enter a number: 8
8! = 40320

How it works:

Factorial of a number n is defined as:

n! = n * (n-1) * (n-2) * (n-3) * ..... * 2 * 1

For example:

1
2
5! = 5 * 4 * 3 * 2 * 1 = 120
9! = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 362880

The following table demonstrates what happens at each iteration of the loop (assuming the n = 5):

Iteration fact i
After 1st iteration fact = 1 * 5 = 5 5
After 2nd iteration fact = 5 * 4 = 20 4
After 3rd iteration fact = 20 * 3 = 60 3
After 4th iteration fact = 60 * 2 = 120 2
After 5th iteration fact = 120 * 1 = 120 1

Recommended Reading: