• Register
1,240 points
15 11 8

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

 

More Posts

Generate random numbers between 1 and 100 in C++ Lalit Kumar - May 12, 2020
How to generate random numbers between 0 and 1 in C++( with explanation )? Lalit Kumar - Jun 23, 2020
How to generate random numbers between 0 and 1 in C++? Lalit Kumar - May 15, 2020
how to generate random numbers with a range in C++? Lalit Kumar - Apr 17, 2020
How to generate random numbers c++ Sanjana Sagar - May 27
How to generate random numbers in java within range Hasnain_khan - Oct 13, 2020
Java random number between 1 and 11 amna - Oct 18, 2020
C++ Program for game "ROCK PAPER SCISSOR" Lalit Kumar - Jun 22, 2020
Fill array with random numbers in C++ Lalit Kumar - Jun 17, 2020
srand(time(null)) Lalit Kumar - Jun 20, 2020