# Generate random numbers between 1 and 10 in C++

posted May 12, 2020 1 min read

In this article, we are going to learn how to create random numbers between 1 and 10 in C++?

# Solution

• Assign the first number to be 1 and last number to 100

• Calling function rand

• Result

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.

## Mod method

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.

### Program

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

using namespace std;

int main()
{
int no_of_numbers = 10;
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;
}``````