// Roll
a six-sided die 6000 times.
#include
<iostream> // For I/O
#include
<cstdlib> // For rand function
#include
<ctime> // For time function
int main()
{
const int arraySize = 7;
int frequency[ arraySize ] = { 0 };
srand( time( 0 ) ); // seed random-number generator
for ( int roll = 1; roll
<= 6000; roll++ ) //roll 6000 times
{
++frequency[ 1 +
rand() % 6 ]; // replaces 20-line switch
}
//
output frequency elements 1-6 in tabular format
cout << "Face\tFrequency"
<< endl;
for ( int face = 1; face
< arraySize; face++ )
{
cout << face << “\t” << frequency[ face ] << endl;
}
return 0;
// indicates successful program execution
} // end
main
Remake of old program to roll dice from your book. An array is used instead of 6 regular variables, and the proper element can be updated easily (without needing a selection structure).
This creates a number between 1 and 6, which determines the index of frequency[] that should
be incremented.