I need to generate 40 random numbers between 50 and 100 using rand(). How do I do this?

cout << sizeof(a) << endl;
    for(int i = 0; i < 40; i++)
    {
        if(rand() % 1000+1 >= 50 && rand() %1000+1 <= 100)
        a[i] = rand() %1000+1;
    }

I was doing something like this, but it didn't work at all. : S

Your code generates three different random numbers. One to compare to 50, one to compare to 100, and one to put in the array.

Try this:

for(int i = 0; i < 40; i++)
    {
        a[i] = rand()%(max-min + 1) + min;
    }

where max and min are, in your case, 100 and 50

Edited 2 Years Ago by Moschops

Thanks! I love the simplicity and elegance of it.

Edited 2 Years Ago by mixelplik

here is a simpler version and easy to understand

  int compGuess = rand() % 100 +50;
        int highestNumber = 100;
        int lowestNumber = 50;

        // if you wanna change the numbers you can
        // its easier

That code generates random numbers between 50 and 149. Not between 50 and 100.

Edited 2 Years Ago by Moschops

This question has already been answered. Start a new discussion instead.