Hi nerx!
The second way to do it is:
Code:
#include <stdio.h>
int fact(int num); // don't forget the right declaration
int main(int argc, char **argv)
{
int n,res;
printf("Enter a Factorial: ");
scanf("%d",&n);
res = fact(n);
printf("The Factorials of %d = %d\n",n,res);
return 0;
}
int fact(int num)
{
int i = 1, result = 1;
if(num == 0) num = 1;
else while(num > i) result *= ++i;
return result;
}
On my system the limit is by 20! =2.4329e+18
but with your program the result is with greater than 20 wrong.
The storage size of int is 4 byte.
If you would take the data type long the storage size would be 8 byte.
I know it is not really proper to change the data type to long double.
With this you would turn the number of factorials up to 1500!
example:
Code:
#include <stdio.h>
long double fact(long double num);
int main(int argc, char **argv)
{
long double n, res;
printf("Enter a Factorial: ");
scanf("%Lf",&n);
res = fact(n);
printf("The Factorials of %Lf = %Lf\n", n, res);
return 0;
}
long double fact(long double num)
{
long double i = 1, result = 1;
if(num == 0) num = 1;
else while(num > i) result *= ++i;
return result;
}