Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the random number generator work in C?

I'm trying to generate random number between 0 and 40(inclusive). So the code I Implemented is this-

 y=rand()%41;

However everytime I click compile and hit Run. It outputs the same random numbers. As in say for instance I ran this in a loop.

for(i=0;i<4;i++)
{
     y=rand()%41;
     printf("%d ",y);
}

Every single time, the output is the same 4 numbers. It always outputs 14,2,etc etc on the terminal. No matter what.

So my first question is, why is this happening?

and Secondly, how does the random number generator work in C?

I thought since I include time.h library, the numbers are generated through some standard algorithm using the system time. And since the system time is continuously changing, the numbers that are generated should also change every time I run the program.

like image 925
Ole Gooner Avatar asked Dec 21 '25 11:12

Ole Gooner


1 Answers

rand() generates only pseudorandom numbers. This means that every time you run your code you will get exactly the same sequence of numbers.

Consider using

srand(time(NULL))

to get every time different numbers. In fact a possible implementation for rand is

next = next * 1103515245 + 12345;
return (UINT32)(next>>16) & RAND_MAX;

where next is defined as

static UINT32 next = 1;

Calling srand() has the effect of changing the initial value of next, thus changing the "next" value you get as result.

like image 164
Manlio Avatar answered Dec 24 '25 01:12

Manlio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!