In C++, to generate a random number, we use the rand() function from the <stdlib> library.
int rand();However, each time you run the program, the number doesn’t seem so random.
In this case, we set a seed.
A seed is what a program uses to determine the sequence of random numbers in a program. This is because, before a program starts, a special sequence of numbers from 0 to 32767 is decided.
The function srand(seed) determines this special sequence of numbers.
Each time rand() is called, it outputs a number from this special sequence.
Therefore, if the seed in srand(seed) is the same, then the values that will appear will also be the same, no matter how many times you run the program.
Therefore, to generate somewhat unpredictable numbers each time we run the program, we use:
srand(time(0))Here, the time(0) from the <time> library is the current time in the computer system.
Therefore, each time we run the program, the sequence of numbers changes depends on the time of the computer system.
Random Numbers from a Range
If you want to generate a random number from a range of values, we can use a separate function random().
int random (int min, int max) {
int nChoices = max - min + 1;
return (min + (rand() % nChoices));
}Therefore, calling the function random(2, 5) will output a number from 2 and 5.
The way that this works is that:
- After we set a specific range, like
2and5, we want to know how many integers are between that rangenChoices.- To do this, we perform
max - min. - This calculates how many possible integers are between
minandmax. - We then add
1to accommodate the endpoints. - Therefore, in a specific range of numbers between
2and5, there are a total ofor integers between them.
Namely, they are2,3,4, and5.
- To do this, we perform
- Next, we perform the operation
rand() % nChoices.- Since
rand()is a random number between0and32767, we check if it is divisible bynChoicesusing the modulo operator.
This restricts the possible outputs from0tonChoices - 1. - In our previous example, since
nChoicesis4, then the output ofrand() % nChoicesbecomes restricted to0to3.
- Since
- We finally add
minto our output.- We don’t want to output random numbers from
0to4so we adjust that to accommodate our original range: from2to5. - To do this, we simply add
mintorand() % nChoices.
- We don’t want to output random numbers from
Make sure that you have srand(seed) set up in your main() to ensure unpredictable outputs.
Displayed below is one example of how it can be used.
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
int random (int min, int max) {
int nChoices = max - min + 1;
return (min + (rand() % nChoices));
}
int main () {
int number = random(5, 10);
cout << number;
return 0;
}