# Printing values of psuedo random numbers in a range

I wanted to write a program to print the values of pseudo random numbers in a range. So, i wrote the following:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i=0,x;
while(i!=10)
{
srand(time(0));
x=rand()%51;
if(x>=30&&x<=45)
{
printf("%d\n",x);
i++;
}
}
return 0;
}


But this program is printing some random number between 30 and 45 10 times(the same value, say 33 ten times). Can someone please explain the flaw in this?

• While this looks like a programming question, I would argue that there is more to it than that. See my answer. – Yuval Filmus Apr 2 '20 at 13:44

While this looks like a programming question, the real misunderstanding is in how to use pseudorandom number generators.

A pseudorandom number generator is initialized using a seed (we later expand on that). Once initialized, it can be called to output a (seemingly) infinite sequence of random bits or integers (the sequence will be periodic, but the period can be huge). The interface of a pseudorandom number generator thus consists of two functions:

• Initialize with a seed – in your case, srand.
• Output the next number in the sequence – in your case, rand.

For some reason, you are initializing the seed each time you want a random number. While this is not necessarily wrong (though in your case it is!), it ignores a fundamental feature of most pseudorandom number generators: initializing is slow, and generation is fast. We can effort initialization to be slow since it is only called once, whereas you could be generating many numbers. This is why it is not recommended to initialize your generator for each generated number.

What goes wrong with your code? The problem is that time returns a value which only changes once a second. Since your program executes in much less than a second, it is highly likely that each time you initialize your generator, you will initialize it using the very same value. Therefore you are getting the same number each time – this is by design.

Finally, a few words on how to initialize your generator. One option is to choose a seed at random once and for all. This guarantees that your results are reproducible – each time you run the program, it will be using the same pseudorandom sequence. Another popular option is to use the current time, as you're doing (though it's better to use something with higher resolution than seconds). A third option is to use some "entropy reservoir", such as the Unix /dev/random, which is supposed to pick up entropy from key presses, mouse moves, and so on. A fourth option would be to use thermal noise – that requires specialized hardware.