D.2
Random Number Generation
With the use of stdlib.h the two functions srand() and rand() can be used to generate random numbers. The function srand() is used to seed or initialize the random number generator. Once the random number generator has been initialized, the function rand() can be called to return a random number between 0 and RAND_MAX. It is also good to know that if you seed the random number generator with the same seed, it will produce the same set of random numbers each time. One way to obtain a random set of numbers is to use the time() function to seed the random number generator. The example below illustrates the use of these two functions to get a random number between 1 and 10.
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
void main()
{
srand((unsigned)time(NULL)); //seed the random number generator
cout<< (rand() % 10) + 1; //print the random number between 1 and 10
}
Remember that if you did not use the time function in the example above you would continue to get the same random number.
Note: Do not seed the random number generator before each call to rand. Seed the generator once, and then call rand multiple times to achieve more random numbers.