/* A couple decides to have children. They decide to continue to have children until they have at least one boy and one girl. Then they decide to stop having children. This program simulates family size for 20 couples, using a function to help manage complexity. */ #include /* libraries for the pseudo-random number generator */ #include #include /* Within the time.h library, * time returns a value based upon the time of day * Within the stdlib.h library * rand returns a pseudo-random integer between 0 and RAND_MAX */ #define numberOfCouples 20 /* procedure to simulate the number of children for one couple */ void simulate_couple () { /* couple starts with no children */ int boys = 0; int girls = 0; /* couple has children */ while ((boys == 0) || (girls == 0)) { if ((((double) rand()) / ((double) RAND_MAX)) < 0.5) boys++; else girls++; } /* reporting of family size */ printf (" boys: %2d girls: %2d total: %2d\n", boys, girls, boys + girls); } /* procedure to conduct simulation for several couples */ void simulate_several_couples () { int couple; for (couple = 0; couple < numberOfCouples; couple++) { simulate_couple (); } } int main () { /* initialize pseudo-random number generator */ /* change the seed to the pseudo-random number generator, based on the time of day */ srand (time ((time_t *) 0) ); /* print initial title for program */ printf ("Simulation of family size\n"); /* run simulation for several couples */ simulate_several_couples (); return 0; }