/*
* The behavior of rolling a pair of dice.
*
* The total roll can be anywhere from 2 to. We want to count how often each
* roll comes up. We use an array to keep track of the counts: a[2] will count
* how many times we've rolled 2, etc.
*
* We simulate the roll of a die by calling C's random number generation
* function, rand(). Each time rand() is called, it returns a different,
* pseudo-random integer. The values that rand() returns typically span a large
* range. We use C's modulus (or ``remainder'') operator % to produce random
* numbers in the range we want. The expression rand() % 6 produces random
* numbers in the range 0 to 5, and rand() % 6 + 1 produces random numbers in
* the range 1 to 6.
*/
#include <stdio.h>
#include <stdlib.h>
main ()
{
int i;
int d1, d2;
int a[13]; /* uses [2..12] */
/* Initialize: */
for (i = 2; i <= 12; i++)
a[i] = 0;
/* Compute: */
for (i = 0; i < 1000; i++) {
d1 = rand () % 6 + 1;
d2 = rand () % 6 + 1;
a[d1 + d2] = a[d1 + d2] + 1;
}
/* Print out: */
for (i = 2; i <= 12; i++)
printf ("%2d: %3d\n", i, a[i]);
return 0;
}
|