This post will discuss how to generate random numbers in the specified range in C++.

1. Using std::uniform_int_distribution

A simple solution to produce random numbers between two values (inclusive) in modern C++ is using std::uniform_int_distribution, which generates random integer values uniformly distributed on a specified closed interval.

The following solution produces high-quality integer random numbers in the given closed interval with std::uniform_int_distribution. It uses std::random_device to obtain seed for the standard mersenne_twister_engine std::mt19937, based on the Mersenne Twister algorithm.

Download  Run Code

 
The above solution is short and elegant, but it is available only on C++11 compliant compilers. Before C++11, you can use Mersenne Twister by boost library.

Download Code

 
There are several other predefined random number generators in header <random>, as listed here. The following solution uses std::default_random_engine random number generator with std::uniform_int_distribution.

Download  Run Code

 
Consider seeding the std::default_random_engine random number generator with the current time.

Download  Run Code

2. Using rand() function

Another common, but less preferred way to generate random numbers in the specified range is using the rand() function. It is defined in the header <cstdlib> and returns a random value between 0 and RAND_MAX (both inclusive). To generate a random value in the closed range [low, high], you can use the expression low + rand() % (high - low + 1), after seeding the rand() function with a random value (say current time).

Download  Run Code

3. Using std::experimental::randint

Although experimental, std::experimental::randint generates a random integer in the specified closed interval. It is defined in <experimental/random> header.

Download  Run Code

That’s all about generating random numbers in the specified range in C++.