I'm trying to
- Get rid of the info in an array with 10 "spots".
- 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++)
{
srand(time(NULL));
randNumber = rand() % 10 + 1;
printf("Random number saved in the array: %d\n", randNumber);
i++;
}
getchar();
getchar();
return 0;
}
2 Answers 2
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++)
to
for (int i = 0; i < 10; i++)
to stay within bounds.
Comments
Your array's size is 10, and this loop runs 11 times, causing an overflow. This will solve it:
for (int i = 0; i < 10; i++)
Also remove the increasing of the loop's iterator, i, from inside the loop body. Remove the line:
i++;
srand()does not create the random numbers.rand()actually gives you the random numbers.srand(time(NULL));means "pick the pseudo random number sequence#1474983934" (#1474983935in the next second). Afterwards,rand()means "pick the next number in the selected sequence". If you always restart the same sequence and always pick the first number thereof, you always get the same number. Solution: move thesrand()call outside the loop.for ( i = 0; i < 10; i++ ) numbers[i] = i+1;), then do a random shuffle on the array.