Question
Write a program that prompts the user to toss a coin a set number of times and then determines how many times heads and tails were flipped.
The program should prompt the user to enter a random seed. Use “Enter a random seed: ” as the prompt. After reading the random seed, use it seed the random number generator. Then prompt the user to enter the number of coin tosses. Use “Enter the number of coin tosses: ” as the prompt. Use this information to create a variable length array whose size is equal to the number of coin tosses. Then use the
rand() function to simulate a coin toss, where 0 represents heads, and 1 represents tails. After flipping the coin the appropriate number of times, print the number of times that heads was rolled, followed by the number
of times that tails was rolled. You must use the following variable names for your program:
seed – stores random seed (unsigned integer)
i – counter variable (integer)
tosses – stores the number of tosses (integer)
tails – stores the number of tails (integer)
heads – stores the number of heads (integer)
results – stores the results of each toss (integer array)
NOTE: You must store the result of each coin flip into
an element of the results[] array if you want credit for this problem.
Explanation / Answer
void enqueue(int *q,int *tail, int element); 2 int dequeue(int *q,int *head); 3 int full(int tail,const int size); 4 int empty(int head,int tail); 5 void init(int *head, int *tail); 01 /*initialize queue pointer*/ 02 void init(int *head, int *tail) 03 { 04 *head = *tail = 0; 05 } 06 /* enqueue an element 07 precondition: the queue is not full 08 */ 09 void enqueue(int *q,int *tail, int element) 10 { 11 q[(*tail)++] = element; 12 } 13 /* dequeue an element 14 precondition: queue is not empty*/ 15 int dequeue(int *q,int *head) 16 { 17 return q[(*head)++]; 18 } 19 /* report queue is full nor not 20 return 1 if queue is full, otherwise return 0*/ 21 int full(int tail,const int size) 22 { 23 return tail == size ? 1 : 0; 24 } 25 26 /* report queue is empty or not 27 return 1 if the queue is empty, otherwise return 0*/ 28 int empty(int head, int tail) 29 { 30 return head == tail ? 1 : 0; 31 } view source print? 01 #include 02 #include 03 #include "queue.h" 04 #define size 3 05 void main(){ 06 int head,tail,element; 07 int queue[size]; 08 // initialize queue 09 init(&head,&tail); 10 // enqueue elements 11 while(full(tail,size) != 1){ 12 element = rand(); 13 printf("enqueue element 14 %d ",element); 15 enqueue(queue,&tail,element); 16 printf("head=%d,tail=%d ",head,tail); 17 //press enter to enqueue more 18 getchar(); 19 } 20 printf("queue is full "); 21 // dequeue elements from 22 while(!empty(head,tail)){ 23 element = dequeue(queue,&head); 24 printf("dequeue element %d ",element) 25 //press enter to pop more 26 getchar(); 27 } 28 printf("queue is empty "); 29 getchar();}