How to loop data into an array

Jun 28, 2018 at 7:53pm
When the user enters a number of iterations I want to generate that many random numbers between 0-40 and store them into an array.

I have the random numbers working properly but I'm stuck on figuring out how to store them into an array. How do I do this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  void prompt_user(int& iterations)
{
    cout << "\nThis program simulates thruster use for docking with ISS." << endl;

    cout << "\nEnter the number of iterations to run: ";

    cin >> iterations;

}

int generate_data(int iterations)
{
    srand((unsigned)time(0));

    int thrusters[iterations];

    int i;

    for (i = 0; i < thrusters[iterations]; i++)
    {
        int num = rand() % 40; // getting random number between 0-40

        thrusters[iterations] = num;
    }

    return iterations;
}
Jun 28, 2018 at 8:14pm
1. main() method is missing
2. You're returning 'iterations' in generate_data(), which is the same as the parameter passed in.
3. loop section has issues w/ the condition and not making use of 'i' in the assignment. You're also not making use of 'num', so can get rid of that
1
2
for (int i=0; i<iterations; ++i)
    thrusters[i] = rand() % 41;

3a. rand() % 41 is from 0 to 40, inclusive. What you had would be from 0 to 39, inclusive (think about what rand() actually is and what modulus operator does). Supposed to use std::random_device or so, as it's better at uniform randomization.
1
2
3
#include <random>
std::random_device rd;
rd() % 41;


4. Should make the generate method of type 'void' and add another parameter, the pointer to the 'thrusters' array. 'thrusters' array should be declared in main.
5. Ideally you want to use more modern C++ structures like vectors for dynamic array -- what you have there is the C-style which comes with limited features and some extra manual management.
Last edited on Jun 28, 2018 at 8:20pm
Jun 28, 2018 at 8:42pm
I actually managed to figure everything out because of this. Thank you so much!
Last edited on Jun 28, 2018 at 9:09pm
Topic archived. No new replies allowed.