C++ (pseudo)random number generation

The following code will generate a (pseudo)random number.

cout << rand() << endl;

The first line seeds the random number generator based on the current time. This only needs to be called once.

The second line outputs a random number to the console that will be in the millions range.

To specify an upper boundary to the random number generated, change the code as such:

cout << (rand() % 20) + 1 << endl;

This bit of code will generate a number between 1 and 20. The +1 ensures 0 is not a valid response and also ensures 20 is included in the range.

Leave a Reply