Next: Arrays as parameters of Up: Arrays Previous: Example Program: Printing Outliers

Example Program: Test of Random Numbers

The following program simulates the throwing of a dice by using a random number generator to generate integers in the range 0 to 5. The user is asked to enter the number of trials and the program outputs how many times each possible number occurred.

An array has been used to hold the six counts. This allows the program to increment the correct count using one statement inside the loop rather than using a switch statement with six cases to choose between variables if separate variables had been used for each count. Also it is easy to change the number of sides on the dice by changing a constant. Because C++ arrays start at subscript 0 the count for an i occurring on a throw is held in the i-1th element of this count array. By changing the value of the constant die_sides the program could be used to simulate a die_sides-sided die without any further change.

#include <iostream.h>
#include <stdlib.h>    // time.h and stdlib.h required for
#include <time.h>      // random number generation

void main()
{
  const int die_sides = 6;    // maxr-sided die
  int count[die_sides];       // holds count of each
                         // possible value
  int no_trials,         // number of trials
      roll,              // random integer
      i;                 // control variable
  float sample;          // random fraction 0 .. 1

      // initialise random number generation and count
      // array and input no of trials
  srand(time(0));
  for (i=0; i < die_sides; i++)
    count[i] = 0;
  cout << "How many trials? ";
  cin >> no_trials;

      // carry out trials
  for (i = 0; i < no_trials; i++)
    {
      sample = rand()/float(RAND_MAX);
      roll = int ( die_sides * sample);
           // returns a random integer in 0 to die_sides-1
      count[roll]++;        // increment count
    }

      // Now output results
  for (i = 0; i < die_sides; i++)
    {
      cout << endl << "Number of occurrences of "
           << (i+1) << " was " << count[i];
    }
  cout << endl;
}
Download program.



Next: Arrays as parameters of Up: Arrays Previous: Example Program: Printing Outliers