Step Eleven  Random Numbers

Design a program called random.cpp. The purpose of this program will be to create a random integer between two integers N1 and N2 where N1 < N2.

In order to use random numbers, there are three built-in functions we will need. One of them is the time function.

cout << time(0) << endl;

This prints out the number of seconds since midnight January 1, 1970. Another function is srand.

srand(time(0));

srand "seeds" the random number function rand with the number of seconds since midnight January 1, 1970. That way, each time you run the program, time(0) returns a different integer, so the "seed" is different, and the sequence of random numbers that rand will generate will be different. If you do not call the srand function, every time the program runs, the same sequence of random numbers will be created. If you call the srand function with the same seed each time, the same sequence of random numbers will also be generated. The last function is rand:

cout << rand() << endl;

returns an integer between RAND_MIN and RAND_MAX. You'll need to explore your system header files to see what those are defined to be on your particular system.

Finally, what we really want is a random number between N1 and N2 rather than between RAND_MIN and RAND_MAX. Something like the following should do the trick:

rand() % (N2 - N1 + 1) + N1;

You ought to put something this useful into a function, possibly with a prototype like this:

int random(int N1, int N2);

Create the function and exercise it a little. We will use it in our next lesson.

Advance to Step Twelve