-1

I'm new to C and I am currently trying to make a randomly generated array of ints. I think I've almost got it but wanting it to have a range of 0 to 1000. Also the output I'm not sure how to format.

            srand ( time(NULL) );
            int myArray[5] = {};
            int randomIndex = rand() % 100;
            int myArray[randomIndex];
            printf("Random: %d\n", myArray);
Ste
  • 7
  • 2
  • 4
    The way to get a random number in the range `0` to `1000` is with `rand() % 1001`. However the code has several issues apart from being an incomplete program, and the compiler should advise you. It is also unclear what you intend. – Weather Vane Dec 12 '18 at 18:55
  • 1
    You cannot define `myArray` two times. – Gerhardh Dec 12 '18 at 19:09
  • 1
    You state that you want to randomly generated array of ints, but your code creates an array of a random size, and then does not initialize the contents of this array. In order to initialize the the contents you will need to iterate over the each element in the array and assign the value of myArray[i] to a random number. To print the contents, you will also need to iterate over myArray and print each element separately. – Tom Drake Dec 12 '18 at 19:09
  • Thanks for the information, will do some more research then have another crack at it. – Ste Dec 12 '18 at 19:20
  • Use a `for loop` to iterate over your array after its created. You can use the `loop variable` as the index to your array to assign the random value you generate with each loop – BackDoorNoBaby Dec 12 '18 at 19:27

1 Answers1

1

You are correctly generating the random number in your desired range (well close, you say 1000, but your code says 100).

However, you never assign that random value to an index in the array.

So if you want to assign a random number between your range to every index of an array of size 5, Doing something like the following:

for (int i = 0; i < 5; i++) //populate each array index of array of size 5
{
    myArray[i] = rand() % 1000; //assign random number to index in the array
    printf("Random: %d\n", myArray[i]);
}

Currently what your code is doing is saying myArray[<at random index>] do nothing (likely optimized out altogether by the compiler - would also expect the compiler to complain about a redeclaration of a variable with the same name).

Now, if your question is randomly generating array sizes, that's a different answer all together...

static_cast
  • 1,174
  • 1
  • 15
  • 21