How to print a random amount of numbers with a random number for each number?

I cannot figure out how to make a random number generator that prints out a random amount of numbers between 10 to 15. These numbers also should be random from 20 to 50. Basically, it should look like this when you run it:

Sample Run:
Generating 11 random numbers (11 is a random number between 10 to 15)...
...11 Random Numbers between 20 to 50: 26, 23, 48, 32, 44, 21, 32, 20, 49, 48, 34
Here's my code thus far. It's bad, I know.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{


int random_integer;
int random_size = 10 + rand()%5;

    cout <<"Generating " << random_size << "random numbers" << random_size << " (is a random number between 10 to 15).";
    for(random_size) { //
    random_integer = 20 + rand()%30; // Random number between 20 and 50


    cout << random_integer <<", ";
}
return 0;
}




Not sure what goes in the conditional statement in the for loop
Last edited on
First of all, please use proper indentation, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
    int random_integer;
    int random_size = 10 + rand()%5;

    cout <<"Generating " << random_size << "random numbers" << random_size << " (is a random number between 10 to 15).";
    
    for(random_size) { //
        random_integer = 20 + rand()%30; // Random number between 20 and 50
        
        cout << random_integer <<", ";
    }
    return 0;
}


It's not much work and will make the code easier to read for you and others. I almost overlooked your for statement.

In C++, the for loop should look like this:

1
2
3
for(int i = 0; i < random_size; i++) { 
    // do stuff 
}


This is equivalent to

1
2
3
4
5
int i = 0;
while(i < random_size) {
    // do stuff
    i++;
}


A few additional things:

1. Output style: You might want to use new lines after the "Generating..." message.
Also in the for loop, you could add a if (i != random_size - 1) condition for the comma output, to prevent the comma after the last digit.

2. A little variation, that might be useful for you soon: the for-each loop. If you have an iterable (a vector, an array etc.) you can do for (element : iterable) {..} to go over all elements in the vector or array.
Last edited on
Topic archived. No new replies allowed.