Skip to main content

Random numbers

Sometimes we want to generate some numbers to quickly fill in variables, create unpredictability in our programs or even conduct statistical simulations.

To handle these scenarios, both in C and C++ you can generate random numbers using the rand() function, which produces a pseudorandom integer.

Usage​

The rand() function in C++ is part of the C Standard Library. It generates a random integer number between 0 and RAND_MAX, which is a constant that can vary depending on the compiler used but is generally 32767 (215 - 1) or 2147483647 (for 32-bit).

The numbers it generates are called "pseudo-random" because they appear to be random, but they are actually determined by an initial seed value and a deterministic, predictable algorithm. This means that if you use the same seed, calling rand() will give you the same sequence of numbers every time you run the program.

We can try running this program multiple times and see if the number changes:

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
int randNum = rand();

cout << randNum;

return 0;
}

Output​

The output will always be:

41
note

A different number might be generated by the program, depending on the compiler you are using (also, we didn't specify the seed so it's 1 by default). The point is, that the generated value won't change no matter how many times you run your program.

Using srand() & time()​

To use rand() (in a way that the numbers generated are not easily predictable), we need to include the <cstdlib> header and call srand() to initialize the random number generator with a seed value.

We use the srand() function to set a seed for the (pseudo)random number generator and, at the same time, we use the function time() present in the <ctime> header to get a different seed each time the program is run.

The line of code for doing that looks like this:

srand(time(NULL)); // or 0

This line is usually written at the top of the main function.

time() returns the number of seconds since 00:00 hours, Jan 1, 1970 UTC, also known as the "Unix Timestamp". Therefore, since we run the program at a different moment every time, we always get a different seed, and so, a unique random sequence. Of course, this is not really random since you get the same number if you find out the seed used, but it's usually enough for most randomization needs.

Numbers in range​

With rand() we can generate random numbers, but we can't decide if they should be inside a specific range or interval of values.

To do that, there are two common solutions.

Modulo​

If the range starts at 0, we can set the maximum limit using the modulo operator (%).

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
srand(time(NULL));

int randNum = rand() % 100; // 0-99

cout << randNum << endl;

return 0;
}

Of course, you can add 1 to get a range from 1 to 100 in this example.

Formula​

If the range doesn't start at 0, or in other words, the minimum is greater than 0, we can set the interval in the following way:

int randNum = rand() % (max - min + 1) + min;

Where max and min are variables for the maximum and minimum number that you want to generate. This is how it works:

  • rand() generates a random integer.
  • (max - min + 1) calculates the range of possible values. For example, if you want to generate random numbers between 10 and 20, this part evaluates to 20 - 10 + 1 = 11.
  • % (modulo) ensures that the random number falls within the range specified in step 2. If the random number exceeds the range, the modulo operation "wraps" it back into the range.
  • + min shifts the range from 0 to the desired range specified by min. In our example, it shifts from 0 to 10.