How to generate different random numbers in a loop in C++?

C++Server Side ProgrammingProgramming

Let us see how to generate different random numbers using C++. Here we are generating random numbers in range 0 to some value. (In this program the max value is 100).

To perform this operation we are using the srand() function. This is in the C++ library. The function void srand(unsigned int seed) seeds the random number generator used by the function rand.

The declaration of srand() is like below −

void srand(unsigned int seed)

It takes a parameter called seed. This is an integer value to be used as seed by the pseudo-random number generator algorithm. This function returns nothing.

To get the number we need the rand() method. To get the number in range 0 to max, we are using modulus operator to get the remainder.

For the seed value we are providing the time(0) function result into the srand() function.

Example

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
main() {
   int max;
   max = 100; //set the upper bound to generate the random number
   srand(time(0));
   for(int i = 0; i<10; i++) { //generate 10 random numbers
      cout << "The random number is: "<<rand()%max << endl;
   }
}

Output

The random number is: 6
The random number is: 82
The random number is: 51
The random number is: 46
The random number is: 97
The random number is: 60
The random number is: 20
The random number is: 2
The random number is: 55
The random number is: 91
raja
Published on 25-Apr-2019 14:06:02
Advertisements