# 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 at 13:44

• Initialize with a seed – in your case, srand.
• Output the next number in the sequence – in your case, rand.
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.