outputting same number into randnum array

so this array is supposed to have between 20 and 30 elements and it seems to be doing that fine, but then it is supposed to generate random numbers into each of these elements (values between 100-200). After it generates the first number it just seems to repeat it. What am I doing that isn't having it populate with a new number in each element?

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
28
29
30
31
32
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int randint(int min, int max);

int main()
{
    int X = randint(20, 30);
    int ARRAY1[X], ARRAY2[X];
    int j;

    for (j = 0; j < X; j++)
    {
        ARRAY1[j] = randint(100, 200);
        cout << ARRAY1[j] << endl;
    }

    cout << endl;

    system("pause");

    return 0;
}

randint(int min, int max)
{
    int iseed = time(NULL);
    srand(iseed);
    return min + rand() % (max - min + 1);
}
heres the output


158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158
158

Press any key to continue . . .
closed account (E0p9LyTq)
You should only call srand ONCE. Preferably before you do any calls to rand. Not multiple times whenever you want a random number.

Move line 30 in your custom function to before line 10 in main.
Don't seed the legacy rng each time. Seed it once, at the beginning of the program.

C++ does not support C99 VLAs; use std::vector instead.
see: https://cal-linux.com/tutorials/vectors.html

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
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

int randint(int min, int max);

int main()
{
    // seed the legacy rng once, at the start of the program
    std::srand( std::time(nullptr) ) ;

    int x = randint(20, 30);
    std::vector<int> array1(x) ;

    for( std::size_t j = 0 ; j < array1.size() ; ++j )
    {
        array1[j] = randint(100, 200);
        std::cout << array1[j] << ' ' ;
    }
    std::cout << '\n' ;
}

int randint(int min, int max)
{
    return min + std::rand() % (max - min + 1);
}

http://coliru.stacked-crooked.com/a/31a238801578d247
closed account (E0p9LyTq)
Plus....

Variable Length Arrays/Non-constant Length Arrays (line 11) should cause an error, they are not allowed in C++ any more.

If your compiler allows them it is seriously outdated.
Last edited on
@FurryGuy, your solution just about did it, I had to move line 29 as well to define iseed. As for variable length arrays, I don't know, this was a bit of a project that I am working on for a class and the random amount of elements are required. now I have to figure out how to reverse the order and double the values of the variables. I assume he wants me to use pointers to do it
Topic archived. No new replies allowed.