How to use function srand() with time.h?

user2273202 picture user2273202 · May 15, 2013 · Viewed 163.1k times · Source

My program contains code that should generate a random positive integer number every time I execute it. It generates random numbers but only once. After that, when I execute same code, it gives me same values, and it is making my code useless.

I started with the rand function, and then I used the srand() function with the time.h header file, but still it is not working properly.

#define size 10
for(i=0;i<size;i++)
    Arr[i] = rand()%size;

First call (random):

6 0 2 0 6 7 5 5 8 6

Second call (random but same as previous):

6 0 2 0 6 7 5 5 8 6

Later I visited Stack Overflow questions and I read about the srand() function, and I used it as:

#include<time.h>
for(i=0;i<size;i++)
    Arr[i] = srand(time(NULL));

First call:

-10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327

Second call:

-10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326

It is giving me different (but not random values). I've defined Arr[i] as unsigned int, and still I am getting negative values.

Answer

Paul R picture Paul R · May 15, 2013

You need to call srand() once, to randomize the seed, and then call rand() in your loop:

#include <stdlib.h>
#include <time.h>

#define size 10

srand(time(NULL)); // randomize seed

for(i=0;i<size;i++)
    Arr[i] = rand()%size;