In order to use random numbers, there are three built-in functions we will need. One of them is the time function.
This prints out the number of seconds since midnight January 1, 1970. Another function is srand.
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:
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:
You ought to put something this useful into a function, possibly with a prototype like this:
Create the function and exercise it a little. We will use it in our next lesson.
Advance to Step Twelve
Return to the Table of Contents