C Program to Find Factorial of a Any Number
The factorial of a any integer n is equal to 1*2*3*...n. You will learn to calculate the factorial of a number using for loop in this example.
The factorial of a positive number n is given by:
factorial of n (n!) = 1*2*3*4....n
The factorial of a negative number n is given by:
factorial of -n (-n!) = -1*-2*-3*-4....-n
And, the factorial of 0 is 1,
0! = 1
Example: Factorial of a Number
#include<stdio.h>
#include<conio.h>
int main()
{
int a;
int fact=1;
printf("Enter an integer: \n");
scanf("%d", &a);
if(a<0)
{
a=-a;
for(int i=1; i<=a; i++)
{
fact=fact*i;
}
printf("Factorial of the %d=%d", -a, -fact);
return -fact;
}
else
{
if(a>0)
{
for(int i=1; i<=a; i++)
{
fact=fact*i;
}
printf("Factorial of the %d = %d", a, fact);
return fact;
}
else
{
if(a==0)
{
printf("The factorial of %d = 1", a);
}
}
}
getch();
}
Output 1:
Enter an integer: 10 Factorial of 10 = 3628800
Output 2:
Enter an integer: -10 Factorial of 10 = -3628800
Output 3:
Enter an integer: 0 Factorial of 0 = 1
This program takes a positive integer from the user and computes factorial using for loop.
Since the factorial of a number may be very large, the type of factorial variable is declared as
unsigned long long
.
If the user enters negative number, the program displays error message.
Post a Comment
Thanks For Your Comment. We will reply you as soon as possible ...
EmoticonClick to see the code!
To insert emoticon you must added at least one space before the code.