Page 162 - DCAP507_SYSTEM_SOFTWARE
P. 162
System Software
Notes
Example: Here is a slightly larger example of the use of arrays. Suppose we want to
investigate the behavior of rolling a pair of dice. The total roll can be anywhere from 2 to 12, and
we want to count how often each roll comes up. We will use an array to keep track of the counts:
a[2] will count how many times we've rolled 2, etc.
We'll simulate the roll of a die by calling C's random number generation function, rand(). Each
time you call rand(), it returns a different, pseudo-random integer. The values that rand() returns
typically span a large range, so we'll 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.
Here is the program:
#include <stdio.h>
#include <stdlib.h>
main()
{
int i;
int d1, d2;
int a[13]; /* uses [2..12] */
for(i = 2; i <= 12; i = i + 1)
a[i] = 0;
for(i = 0; i < 100; i = i + 1)
{
d1 = rand() % 6 + 1;
d2 = rand() % 6 + 1;
a[d1 + d2] = a[d1 + d2] + 1;
}
for(i = 2; i <= 12; i = i + 1)
printf("%d: %d\n", i, a[i]);
return 0;
}
We include the header <stdlib.h> because it contains the necessary declarations for the rand()
function. We declare the array of size 13 so that its highest element will be a[12]. (We're wasting
a[0] and a[1]; this is no great loss.) The variables d1 and d2 contain the rolls of the two individual
dice; we add them together to decide which cell of the array to increment, in the line
a[d1 + d2] = a[d1 + d2] + 1;
After 100 rolls, we print the array out. Typically (as craps players well know), we'll see mostly
7's, and relatively few 2's and 12's.
By the way, it turns out that using the % operator to reduce the range of the rand function is not
always a good idea.
156 LOVELY PROFESSIONAL UNIVERSITY