/*********************************************** ** ** proj4.c -- rolling dice ** ** D. L. Frey ** 1/4/99 ** ** This program simulates rolling a pair of dice 300 times ** It counts the number of times each differet face (1-6) ** occurs and the number of times each total (2-12) occurrs ** ** Algorithm ** ** ** Notes-- ** 1. the array 'count' is defined with size 7 so ** that the code can use indexes 1-6, the values on the ** faces of the dice. count[0] is not used. ** 2. the array 'total' is defined with size 13 so ** that the code can use indexes 2-12, the possible totals ** of the 2 dice. total[0] and total[1] are not used ***********************************************************/ #include #include #include #define ROLLS 300 /* number of rolls of the dice */ #define SEED 44 /* random number seed */ /* prototypes for subroutines */ void printCounts (int a[], int size); void printHistogram (int b[]); main() { /* define arrays to hold counts -- initialized to zero */ int count[7] = {0}; int total[13] = {0}; int i,j , die1, die2; /* initialize the random number generator */ srand (SEED); /* roll the dice ROLLS times ** 1 + rand() % 6 yields an integer between ** 1 and 6, inclusive */ for (i = 0; i < ROLLS; i++) { /* increment count for first die */ die1 = 1 + (rand() % 6); count[die1]++; /* increment count for secnd die */ die2 = 1 + (rand() % 6); count[die2]++; /* increment the count for the total ** of the two dice */ total[die1 + die2]++; } /* call the subroutine printCounts ** to print the contents of the array 'count' */ printCounts (count, ROLLS); /* print historgram for total */ printHistogram (total); } /************************************** ** function printCount ** ** Inputs ** a -- an integer array ** size -- the total of all elements in a ** Outputs ** displays the contents of 'a' on the screen ***************************************/ void printCounts (int a[], int size) { int i; /* print the counts */ printf ("In %d rolls of two dice:\n", size); printf ("Die Occurrences Percentage\n"); for (i = 1; i < 7; i++) { printf ("%2d %3d %0.2f\n", i, a[i], ((float)a[i] / (size * 2)) * 100); } } /****************************************** ** subroutine printHistogram ** ** this subroutine prints a historgram ** using a * to represent each occurrence of ** the total of two dice ** ** Input -- an integer array that is assumed ** to contain the dice totals ** Output -- histogram printed on the screen *****************************************/ void printHistogram (int b[]) { int i, j; printf ("The sum of the dice were:\n"); /* for each possible total.. */ for (i = 2; i < 13; i++) { /* print readable total */ printf ("%2d occurred %3d times: ", i, b[i]); /* print a * for each time that total occurred */ for (j = 0; j < b[i]; j++) { printf ("*"); } /* go to the next line */ printf ("\n"); } }