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 2 and 5, we want to know how many integers are between that range nChoices.
    • To do this, we perform max - min.
    • This calculates how many possible integers are between min and max.
    • We then add 1 to accommodate the endpoints.
    • Therefore, in a specific range of numbers between 2 and 5, there are a total of or integers between them.
      Namely, they are 2, 3, 4, and 5.
  • Next, we perform the operation rand() % nChoices.
    • Since rand() is a random number between 0 and 32767, we check if it is divisible by nChoices using the modulo operator.
      This restricts the possible outputs from 0 to nChoices - 1.
    • In our previous example, since nChoices is 4, then the output of rand() % nChoices becomes restricted to 0 to 3.
  • We finally add min to our output.
    • We don’t want to output random numbers from 0 to 4 so we adjust that to accommodate our original range: from 2 to 5.
    • To do this, we simply add min to rand() % nChoices.

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;
}