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:
srand()You get the same sequence because
rand()is automatically seeded with the a value of 1 if you do not callsrand().Edit
Due to comments
rand()will return a number between 0 andRAND_MAX(defined in the standard library). Using the modulo operator (%) gives the remainder of the divisionrand() / 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 applyrand() % 1000.