niyz niyz - 1 year ago 104
C Question

Assigning a random value to an array

I'm trying to

  1. Get rid of the info in an array with 10 "spots".

  2. Fill the array with (10) random numbers

My code till time

int main()
int numbers[10] = { 0 };
int randNumber = 0;
int i = 0;

for (int i = 0; i <= 10; i++)
randNumber = rand() % 10 + 1;
printf("Random number saved in the array: %d\n", randNumber);

return 0;

Answer Source

First of all, you need to move the srand(time(NULL)); out of the loop.

Otherwise, because, time() has a time granularity of 1 second, in a second, if called multiple times in the loop (within a second, probably), it will re-initialize the PNRG with the same seed and all the next call to rand() will give you the same random number.

Now, once you have the random numbers, you need to assign it to the each array member like numbers[i] = randNumber; inside the loop, but there's more to it. Your loop, at present is off by one. You need to change

  for (int i = 0; i <= 10; i++)


 for (int i = 0; i < 10; i++)

to stay within bounds.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download