Random number generation in C/C++

In C/C++, pseudorandom numbers can only be retrieved if a seed is used. The seed must be unique every time the program is executed, since they are simply a big loop of numbers that depend of that seed number. If the same seed is used on every execution, the exact same cycle will be generated, with its numbers in the same order. You don’t want that.

A very good way to get unique pseudorandom sets of numbers is by using the time function. First, you must include these two libraries: stdlib.h + time.h for C, or cstdlib + ctime for C++.

Now to the code. First generate the seed, then generate your random number:

srand(time(NULL));
int r = rand();

Your pseudorandom number r will be a number between 0 and RAND_MAX, a constant defined in . Its default value may be different depending on the implementation, but it is guaranteed to be at least 32767.

If you want to get a smaller random number, you can use the modulo of that number, like this:

r = rand() % 100;

This way you’ll get a number between 0 and 99.

Remember to generate the srand() seed only once in your program.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: