C Program to Find Factorial of a Number

A factorial of a number can be defined as the multiplication of the number itself and its descending natural numbers. Factorial is denoted by ‘!’ symbol. e.g. the factorial of 5 is

5! = 5 x 4 x 3 x 2 x 1 = 120

The factorial of 1 is

1! = 1

C program to find the factorial of a number is shown below. 

Program

#include<stdio.h>
int main()
{
    int i,n,fact=1;
    printf("Enter a number \n");
    scanf("%d",&n);
    for (i=1;i<=n;i++)
    {
        fact=fact*i;
    }
    printf ("The factorial of %d is %d",n,fact);
    return 0;
}

Here, the number entered by the user is stored in variable n. The loop goes on from 1 to the number itself and inside the for loop, the working of the expression can be understood from the following steps.


Let us suppose, the user has entered 4

In first loop,

i=1 so
fact = 1 * 1 = 1

In second loop,

i=2 so
fact = 1 *2 =2

In third loop,

i=3 so
fact = 2 * 3 = 6

In fourth loop,

i =4 so
fact = 6 * 4 = 24

which is the final result as 4! = 24.

Output:

Enter a number
6

The factorial of 6 is 720