/* 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 functions to help manage complexity. Function parameters specify the number of couples and the fraction of boys born. */ #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 parameter fraction_boys: the percentage of boys born, expressed as a decimal fraction */ void simulate_couple (double fraction_boys) { /* 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)) < fraction_boys) 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 parameter numCouples: the number of couples to be simulated parameter fraction_boys: the percentage of boys born, expressed as a decimal fraction */ void simulate_several_couples (int numCouples, double fraction_boys) { printf ("simulation with fraction of boys: %6.3lf\n", fraction_boys); int couple; for (couple = 0; couple < numCouples; couple++) { simulate_couple (fraction_boys); } } 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 */ double boy_fraction; for (boy_fraction = 0.5; boy_fraction <= 0.52; boy_fraction += 0.002) { simulate_several_couples (numberOfCouples, boy_fraction); } return 0; }