Ariannun Ariannun - 1 month ago 20
C++ Question

Write a program that will generate 1000 random integers in the range 0-49. (C++)

I've looked around other questions asked here but can't quite find what I need.

I've got this question;

Write a program that will generate 1000 random integers in the range 0-49. It should count and report how many were in the range 0-24 and how many were in the range 25-49.

and this is what I have so far;

#include<iostream>
#include<ctime> //For time()
#include<cstdlib> //For rand() and srand()


using namespace std;
int main()
{
int x;
int counter = 0;
int y = 0;
int z = 0;

srand(time(NULL));



for (counter = 0; counter < 1000; counter++) {
{
x = rand() % 49 + 1;
if (x >= 0 && x <= 24)
{
y++;
}
else if (x > 24 && x <= 49)
{
z++;
}
}

cout << "Number of numbers between 0-24: " << y << endl;
cout << "Number of numbers between 25-49: " << z << endl;



system("pause");
return 0;
}
}


It loops once but I can't understand how to get it to loop over and over until 1000 numbers have been generated and categorized.

I'm pretty new to C++ so could someone explain how to get this to loop? Have I missed something super obvious?

Answer

Ya gots one too many curly brackets in your for loop. Becuase of that, your return and couts are happening within the for loop. It gets one number, prints out, then gets returned before it can come back around. Try this:

#include<iostream>
#include<ctime>   //For time()
#include<cstdlib> //For rand() and srand()

using namespace std;
int main()
{    
    srand(time(NULL));

    for (counter = 0; counter < 1000; counter++)
    {
        int x;            //See Note #3 Below
        int counter = 0;
        int y = 0;
        int z = 0;
        x = rand() % 50;  //See Note #1 Below
        if (x < 25)       //See Note #2 Below
        {
            y++;
        }
        else
        {
            z++;
        }
    }

    cout << "Number of numbers between 0-24: " << y << endl;
    cout << "Number of numbers between 25-49: " << z << endl;

    system("pause");
    return 0;   
 }

3 notes about your Code:

  1. Your random number generator is only getting numbers 1-49, not 0-49.
  2. You don't really need to structure your if statement that way. All you have to do is say, "If it's less than 25, put it in one bucket, otherwise, put it in the other."
  3. You may want to declare variables in the scope they'll be used. In this case, your for loop.