# how to generate random numbers with a range in C++?

posted Apr 17, 2020 2 min read

``````#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
int no_of_numbers = 100;
int first_number = 1;

std::srand(std::time(0));

int random = std::rand() % no_of_numbers + first_number;
for (int i=0; i<10; ++i)
{
random = std::rand() % no_of_numbers + first_number;
std::cout << random << std::endl;
}

return 0;
}
``````

No_of_numbers is the range of the numbers.
First_number it is the lowest number our program will show.
The first thing we need to do is call the function called standard rand this is provided by c standard library we used as a header file
This will give us a value of 0 to rand max rand max will vary by system
How do we turn it into the range of numbers we want?
Let's assume that this rand max value is 5 so the possible number we will reach out to will be 0,1,2,3,4,5
What we need to do here is mod the result of this by our no_of_numbres
Let's say that we want two numbers of what will happen here when we mod
0 mod by 2 will 0
1 mod by 2 is 1
2 mod by 2 is 0
3 mod by 2 is 1
4 mod by 2 is 0
5 mod by 2 is 1
If you're familiar with the modular operator for the modulus operator, it gives the remainder
Of the division
We have narrowed them from this value or this expression to the number of numbers we need
Or we need to shift up to the numbers we need and  we simply do that by adding on our first number so again if we pretend that rand is giving us back a value from a range of 0 to 5 we are modding that by 2 so the min value we will get out of this portion of expression is going to be 0 and the max value we will get 1
If our first no is 1 if we want to modify this into a 1 or 2 then if we add on the first number the minimum value we get 1 and max value is 2 similarly
In the loop, we are going to generate random numbers each time

If we don't use

`` std::srand(std::time(0));``

above expression then we will get the same numbers each time we run the code.