/* File: toss.c Description: The user enters the numbers of fair tosses of a coin and the program computes the number of heads and tails and prints them out. Input: User enters the number of tosses Ouput: Displays the number of fair tosses of heads and tails. Revised from program 6.9 in Bronson page 313 */ /* preprocessor include files found in /usr/include/ directory */ #include /* needed to call printf() and scanf() */ #include /* needed to call srand() and rand() */ #include /* needed to call the time() function */ /* toss is toss a coin a number of times (which is the input) and returns the number of heads, and therefore the number of tails can be computed */ /* prototpe declarations */ int tossCoin(int); void printStats(int, int); int main() { int numTosses, numHeads; /* Generate the first seed value. A NULL arguments forces time() to read the computer's internal time in seconds. The srand then uses this value to initialize rand() */ srand(time(NULL)); printf("How many tosses of a fair coin shall we do? Please enter: "); scanf("%d", &numTosses); printf("Ok, you entered %d tosses, so we'd expect %d heads and %d tails\n", numTosses, numTosses/2, numTosses/2); numHeads = tossCoin(numTosses); printStats(numHeads, numTosses); return EXIT_SUCCESS; } /* printStats function */ void printStats(int heads, int tosses) { printf("The number of heads %d, tails %d\n", heads, (tosses-heads)); } /* tossCoin function */ int tossCoin(int tosses){ int i; int heads = 0; for (i=1; i <= tosses; i++) { if ((1 + (rand()%100)) <= 50) { heads++; } } return(heads); }