Why do I get the same result with rand() every time I compile and run?

Whenever I run this code, I get a same result.

Program

#include<stdlib.h>

int main(int agrc, const char *argv[]) {
 int i = rand();
 printf("%d\n",i);
 for(i=0;i<10;i++) {
  printf("%d\n",rand());
 }
}

Result:

41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705

I ran this on mingw. Actually I am learning Objective-C

Please help me.


Solution 1:

You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()

For example

srand(time(NULL));
rand();//now returns a random number

The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.

So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.

Solution 2:

You want to initialize the PRNG.

Initialize it once (typically inside main()) with a call to the srand() function.

If you do not initialize the PRNG, the default is to have it initialized with the value 1. Of course initializing it with some other constant value will not give you different pseudo random numbers for different runs of the program.

srand(1); /* same as default */
srand(42); /* no gain, compared to the line above */

You need to initialize with a value that changes with each run of the program. The value returned from the time() function is the value most often used.

srand(time(NULL)); /* different pseudo random numbers almost every run */

The problem with time(NULL) is that it returns the same value at the same second. So, if you call your program twice at 11:35:17 of the same day you will get the same pseudo random numbers.

Solution 3:

Just to add to Yacoby's answer - I was slightly surprised that it didn't default to a time-based seed, so I looked up the man page:

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

So if you change your code to use seed(1) you should still see the same output - but seed(time()) will make it change each time.

Solution 4:

The output from rand is pseudo-random, which means that it looks effectively random, but is computed the same way each time, starting from a special value called the seed. With the same seed value, you get the same sequence of random numbers.

To set a different seed, use the standard C function void srand(unsigned int) once in your code before you start generating random numbers. One common way of getting a different sequence of random numbers each time you run the program is to base the seed on the clock time. E.g. srand(clock())