In this article, we are going to learn how to create random numbers between 1 and 100 in C++?
The function rand will give us a value of 0 to rand max and the value of rand max will vary from system to system. We will be using the mod method for getting random numbers.
The mod operator (%) in C++ gives us the remainder of two numbers which we used to divide. All the remainders which we get will be narrowed down from this value or this expression the number of numbers we need.
In this code, we are using the loop for creating a random number each time by modifying.
NOTE → Don’t forget to use the syntax std::srand(std::time(0)); If we ignore this syntax then the program will generate all the random numbers each time we run the program.
using namespace std;
int no_of_numbers = 100;
int first_number = 1;
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;