1

I'm trying to display the random numbers that were generated into the array, but the output only displays one number multiple times. I was debugging the code and saw that the array was creating random numbers into it though. I've tried looking online for an answer but nothing seems to allow me to display the random numbers. I'm a super noob and am getting confused. Any information would be greatly appreciated.

main()
{
int unSortedNumbers[10] = { 0 },  i = 0;

for (i = 0; i < US; i++){
    srand((unsigned)time(NULL));
    unSortedNumbers[i] = LB + rand() % (UB - LB + 1);
}
for (i = 0; i < US; i++)
    printf("number %i) is %i.\n", i, unSortedNumbers[i]);
    pause;
}
Brandon
  • 9
  • 6

1 Answers1

2

Try moving srand before the loop:

srand((unsigned)time(NULL));
for (i = 0; i < US; i++){
    unSortedNumbers[i] = LB + rand() % (UB - LB + 1);
}

First of all, srand is supposed to be called once before generating a random sequence.

Second, to explain what you observed, time returns time_t:

For historical reasons, it is generally implemented as an integral value representing the number of seconds elapsed since ....

So perhaps all calls to time happen within the same second and srand was initialized with the same seed. Hence the same numbers.

AlexD
  • 32,156
  • 3
  • 71
  • 65
  • You are a hero of men! Thank you so much, It's working perfectly! – Brandon Sep 26 '14 at 22:07
  • @Brandon I just added a couple of lines to explain possible reason of the same numbers. (Regardless of the fact that `srand` should be used once.) – AlexD Sep 26 '14 at 22:16