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 …

## All 5 Replies

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

(never mind, I see Moschops's answer is spot on.)

Thanks! I love the simplicity and elegance of it.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.