Trace: » moodbox » notes » chapter2 » class_8 » class_notes_30_october » conceptual_blockbusting » imagegallery » unary_scope_resolution_operator » bluetooth_tricolor_led » rolling_a_six-sided_die

Table of Contents

Rolling a Six-Sided Die

rand() % 6

Shifted, scaled integers produced by 1 + rand() % 6

 1   
 2  // Shifted and scaled random integers.
 3  #include <iostream>
 4  using std::cout;
 5  using std::endl;
 6
 7  #include <iomanip>
 8  using std::setw;
 9
10  #include <cstdlib> // contains function prototype for rand
11  using std::rand;                                          
12
13  int main()
14  {
15     // loop 20 times
16     for ( int counter = 1; counter <= 20; counter++ )
17     {
18        // pick random number from 1 to 6 and output it
19        cout << setw( 10 ) << ( 1 + rand() % 6 );      
20
21        // if counter is divisible by 5, start a new line of output
22        if ( counter % 5 == 0 )
23           cout << endl;
24     } // end for
25
26     return 0; // indicates successful termination
27  } // end main

Randomizing the Random Number Generator

Function rand actually generates pseudorandom numbers. Repeatedly calling rand produces a sequence of numbers that appears to be random. However, the sequence repeats itself each time the program executes. Once a program has been thoroughly debugged, it can be conditioned to produce a different sequence of random numbers for each execution. This is called randomizing and is accomplished with the C++ Standard Library function srand. Function srand takes an unsigned integer argument and seeds the rand function to produce a different sequence of random numbers for each execution of the program.

Randomizing the die-rolling program

 
 1 
 2  // Randomizing die-rolling program.
 3  #include <iostream>
 4  using std::cout;
 5  using std::cin;
 6  using std::endl;
 7
 8  #include <iomanip>
 9  using std::setw;
10
11  #include <cstdlib> // contains prototypes for functions srand and rand
12  using std::rand;                                                      
13  using std::srand;                                                     
14
15  int main()
16  {
17     unsigned seed; // stores the seed entered by the user
18
19     cout << "Enter seed: ";
20     cin >> seed;
21     srand( seed ); // seed random number generator
22
23     // loop 10 times
24     for ( int counter = 1; counter <= 10; counter++ )
25     {
26        // pick random number from 1 to 6 and output it
27        cout << setw( 10 ) << ( 1 + rand() % 6 );
28
29        // if counter is divisible by 5, start a new line of output
30        if ( counter % 5 == 0 )
31           cout << endl;
32     } // end for
33
34     return 0; // indicates successful termination
35  } // end main
srand( time( 0 ) );