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

Is it possible to generate different random number, every time loop runs. For example, i have:

for (int t=0;t<10;t++)
{
    int random_x;
    srand ( time(NULL) );
    random_x = rand() % 100;
    cout<<"\nRandom X = "<<random_x;
} 

But the problem is, it generates same random number everytime. Is it possible to generate different random numbers everytime loop runs?

IS there any possibility to reset random number initiallization as well?


Don't use srand inside the loop, use it only once, e.g. at the start of main(). And srand() is exactly how you reset this.


You are getting the same random number each time, because you are setting a seed inside the loop. Even though you're using time(), it only changes once per second, so if your loop completes in a second (which it likely will), you'll get the same seed value each time, and the same initial random number.

Move the srand() call outside the loop (and call it only once, at the start of your app) and you should get random "random" numbers.


Do not use rand(); use new C++11 facilities (e.g. std::mt19937, std::uniform_int_distribution, etc.) instead.

You can use code like this (live here on Ideone):

#include <iostream>
#include <random>
using namespace std;

int main()
{
    // Random seed
    random_device rd;

    // Initialize Mersenne Twister pseudo-random number generator
    mt19937 gen(rd());

    // Generate pseudo-random numbers
    // uniformly distributed in range (1, 100)
    uniform_int_distribution<> dis(1, 100);

    // Generate ten pseudo-random numbers
    for (int i = 0; i < 10; i++)
    {
        int randomX = dis(gen);
        cout << "\nRandom X = " << randomX;
    }
}

P.S.

Consider watching this video from Going Native 2013 conference for more details about rand()-related problems:

rand() Considered Harmful