For many programs you would like a different stream of random numbers for each run.
You could ask the user to supply a different seed for each run, but that would be awkward.
A more convenient method is use the current time as the seed.
The function call time(NULL)
returns the number of seconds since 1 January 1970.
To initialize the random number generator do this:
int srand( time(NULL) )
You will (probably) need to include a header file at the top of your source code:
#include <time.h>
rand()
is not a very good pseudo-random number generator. For
critical work, do not use it. Instead, use a function such as rand48()
from a special purpose library. But rand()
is a standard function,
found on all systems, and works well enough for these puzzles.
Caution: these puzzles are intended only for practice in programming. Random
number generation is tricky. The rand()
function (and functions
that use it) is not not suitable for industrial-grade programs. For serious
work, use a carefully tested numerical library.