0

I'm a beginner with C++, I'm experimenting with arrays and can't seem to figure out how to fill an array with random values. The code below fills the entire array with the same random value. Can anyone tell me what I'm doing wrong?

    const int size = 50; //array size
  int nums[size]; //array

  for(int i = 0; i < size; i++) 
  {
    srand(time(NULL));
    nums[i] = rand() % size + 1; 
  }
leslie
  • 17
  • 2
  • 1
    `srand(time(NULL));` shouldn't be in the loop. it should be invoked at-most once during the process lifetime; ideally near/at the beginning of `main`. – WhozCraig Feb 19 '21 at 20:47
  • 1
    Related, is this code intended to generate a random order of specific unique values in the set 1...size ? Because if so, this won't do that. For that you ideally should (a) create the sequence 1...size, then (b) random-shuffle the sequence. The result will be a sequence of values in 1..size with no duplicates, but random order. – WhozCraig Feb 19 '21 at 20:50

0 Answers0