Here is the function:
int factorial(int x)
{
int i;
int fact = 1;
for(i = 2; i <= x; i = i + 1)
fact = fact * i;
return fact;
}
Here is a driver program: #include
int factorial(int);
int main()
{
int i;
for(i = 1; i <= 7; i = i + 1)
printf("%d %d\n", i, factorial(i));
return 0;
}
The answer to the ``extra credit'' problem is that to portably compute factorials beyond factorial(7), it would be necessary to declare the factorial() function as returning long int (and to declare its local fact variable as long int as well, and to use %ld in the call to printf). 8! (``eight factorial'') is 40320, but remember, type int is only guaranteed to hold integers up to 32767.
(Some machines, but not all, have ints that can hold more than 32767, so computing larger factorials on those machines would happen to work, but not portably. Some textbooks would tell you to ``use long int if your machine has 16-bit ints,'' but why write code two different ways depending on what kind of machine you happen to be using today? I prefer to say, ``Use long int if you would like results greater than 32767.'')
No comments:
Post a Comment