a function to compute the factorial of a number, and use it to print the factorials of the numbers 1-7.

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.'')

Related Links :

No comments:

Post a Comment


If you face any Problem in viewing code such as Incomplete "For Loops" or "Incorrect greater than or smaller" than equal to signs then please collect from My Web Site CLICK HERE


More Useful Topics...

 

History Of C..

In the beginning was Charles Babbage and his Analytical Engine, a machine
he built in 1822 that could be programmed to carry out different computations.
Move forward more than 100 years, where the U.S. government in
1942 used concepts from Babbage’s engine to create the ENIAC, the first
modern computer.
Meanwhile, over at the AT&T Bell Labs, in 1972 Dennis Ritchie was working
with two languages: B (for Bell) and BCPL (Basic Combined Programming
Language). Inspired by Pascal, Mr. Ritchie developed the C programming
language.

My 1st Program...


#include
#include
void main ()
{
clrscr ();
printf ("\n\n\n\n");
printf ("\t\t\t*******Pankaj *******\n");
printf ("\t\t\t********************************\n");
printf ("\t\t\t\"Life is Good...\"\n");
printf ("\t\t\t********************************");
getch ();
}

Next Step...


#include
#include

void main ()
{
clrscr ();
printf ("\n\n\n\n\n\n\n\n");
printf ("\t\t\t --------------------------- \n\n");

printf ("\t\t\t | IGCT, Info Computers, INDIA | \n\n");
printf ("\t\t\t --------------------------- ");

getch ();

}

Hits!!!