Categories
c programming tips and tricks

Smart Random Number Generator

We have this rand() function defined in the stdlib.h for the random number generation. Did you use it and realized that every time you run your program, but it returns the same result.

It’s because, by default, the standard (pseudo) random number generator gets seeded with the number 1. To have it start anywhere else in the series, call the function srand (unsigned int seed).

For the seed, you can use the current time in seconds.

#include <time.h>

// At the beginning of main, or at least before you use rand()
srand(time(NULL));

Annexure:
For your note, the above code seeds the generator from the current second of time. This fact implies that if you expect your program to re-run more than once a second, the given code may not fulfill your requirement. A possible workaround is to store the seed in a file (that you will read later from your program), and you then increment it every time the program is run.

Leave a Reply

Your email address will not be published. Required fields are marked *