This is the first time I'm trying random numbers with C (I miss C#). Here is my code:
int i, j = 0;
for(i = 0; i <= 10; i++) {
j = rand();
printf("j = %d\n", j);
}
with this code, I get the same sequence every time I run the code. But it generates different random sequences if I add srand(/*somevalue/*)
before the for
loop. Can anyone explain why?
You have to seed it. Seeding it with the time is a good idea:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
printf ("Random Number: %d\n", rand() %100);
return 0;
}
You get the same sequence because rand()
is automatically seeded with the a value of 1 if you do not call srand()
.
Due to comments
rand()
will return a number between 0 and RAND_MAX
(defined in the standard library). Using the modulo operator (%
) gives the remainder of the division rand() / 100
. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000
.
i already know this but my question is why does it give the same sequance when i dont use srand ?
Because if you don't seed it manually, it is ALWAYS seeded to 1 by default. See Aditya's answer.
If security is a concern, seeding it with the time is a rather bad idea, as an attacker can often find or guess the startup time relatively easily (within a few dozen to a few hundred attempts), then replay your sequence of pseudorandom numbers. If possible, try to make use of an operating-system-provided entropy source for your seed instead.
If security is a concern, using rand() at all is a rather bad idea, no matter how you seed it. Aside from the unknown strength of the PRNG algorithm, it generally only takes 32 bits of seed, so brute forcing is plausible even if you don't make it extra-easy by seeding with the time. Seeding rand() with an entropy source for security is like giving a donkey steroids and entering it in the [Kentucky] Derby.
"For example, to get a random number in the range of 0-999 we would apply rand()%1000" Be warned, the result is not evenly distributed unless 1000 divides evenly into RAND_MAX+1 (which it probably won't as RAND_MAX is often (2^n)-1), and there are a whole LOT of other problems too. See azillionmonkeys.com/qed/random.html