A directory of Objective Type Questions covering all the Computer Science subjects. Here you can access and discuss Multiple choice questions and answers for various compitative exams and interviews.

C program to find factorial of a number


Problem Description


This program finds the factorial of a given number using the for loop. This is the simplest way to find the factorial of a number. Factorial of a number n is product of all numbers from n to 1. So n factorial is defined as 

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

The factorial of 0 is always 1.


C program to find factorial of a number - Source code
     
                
  /*
C program to find the factorial of a number
 */

#include <stdio.h>

void main()
{
    int i, fact = 1, num;

    printf("Enter the number \n");
    scanf("%d", &num);
    if (num <= 0)
        fact = 1;
    else
    {
        for (i = 1; i <= num; i++)
        {
            fact = fact * i;
        }
    }
    printf("Factorial of %d = %5d\n", num, fact);
}
     
      

Program Output


Case 1:

Enter the number
6
Factorial of 6 =   720

Case 2:

Enter the number
12
Factorial of 12 = 479001600

Program Explanation


1. The program accept a positive integer from the user and calculates its factorial.

2. If the user enter zero as input, its factorial is directly written as 1. Otherwise, its factorial is calculated using the for loop.

3. The for loop iterate up to the entered positive integer starting with 1. In each iteration, the number is multiplied with the result obtained in the previous iteration.

4. When the iterate variable value reaches equal to the entered number, the control exits out of the loop and factorial value is printed.