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
C program to find factorial of a number - Source code
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.
C program to find factorial of a number - Source code
Program Output
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.
need an explanation for this answer? contact us directly to get an explanation for this answer