## C/C++: Get a random number that is in a specific range 1

Assuming you need to generate a random number that is in a specified range, you can do the following:

//int rand(void) creates a pseudo-random number in the range of 0 to RAND_MAX //RAND_MAX is defined in stdlib.h and is the largest number rand will return (same as INT_MAX). const int new_number = (rand() % (maximum_number + 1 - minimum_number)) + minimum_number;

The above code first creates a pseudo-random number that is in the range of `[0, RAND_MAX]`

.

Then it will divide it with the width (+1) of the range we want to use (`maximum_number + 1 - minimum_number`

) and get the remainder (modulo).

The modulo will be in the range of `[0, maximum_number - minimum_number]`

, so we add to it the value of `minimum_number`

to shift the result to the proper range.

This solution, as demonstrated in the example below, works for negative ranges as well.

### Full example of generating `100000`

random numbers that are all in the range `[-31, 32]`

.

const int maximum_number = 31; const int minimum_number = -32; unsigned int i; for (i = 0; i <= 100000; i++) { const int new_number = (rand() % (maximum_number + 1 - minimum_number)) + minimum_number; printf("%d\n", new_number); }