use of srand() in c++

34,529

Solution 1

A random number generator requires a number(it is called seed) to generate random numbers . If the random number generator is given the same seed then every time it will generate the same sequence of random numbers . For example :-

If you run the program and it is generating random sequence 2,78,45,60 . If second time you run the program you will again get the same sequence 2,78,45,60.

srand function is used to change the seed of the random number generator.By setting srand(time(NULL)) , you are setting the seed of the random number generator to the current time.By doing this every time you run the program you will get different random sequences :-

For example for the first run if you are getting 2,78,45,60 . Next time you might get 5,3,6,80 (depending on the current time,as seed has been changed since the time has changed since the last run)

for more info refer these :-

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

http://www.cplusplus.com/reference/clibrary/ctime/time/

Solution 2

rand() doesn't produce a random number - it uses some quite easy formula to compute the next "random value" based on its stored internal state that changes each time a random value is generated. srand() sets that internal state.

This way you can get reproduceable sets of numbers - you call srand() with a given value and rand() then produces a set of values. When you start the program next time and call srand() with exact same value rand() will produce exactly the same set of values. This is useful for simulation.

Calling srand( time( NULL ) ) makes your program generate a set of values that will depend on the current time and therefore be irreproduceable - each time you restart a program a new set of numbers is generated.

Share:
34,529

Related videos on Youtube

Frustrated Coder
Author by

Frustrated Coder

The world is too large to end

Updated on May 30, 2020

Comments

  • Frustrated Coder
    Frustrated Coder almost 4 years

    I am new to c++ so this doubt might look basic but I am not getting the difference between rand() and srand() and what do u mean by "seed" in srand()? when I write srand(time(NULL)), what does it do to generate random numbers, what does time(NULL) do here? and what is it? Thanks in advance

  • Frustrated Coder
    Frustrated Coder about 13 years
    what does NULL stand for in time(NULL)?
  • sharptooth
    sharptooth about 13 years
    @Frustrated Coder: See this (or any other) description - cplusplus.com/reference/clibrary/ctime/time - NULL is an address of wheer to store the current time meaning "don't store the current time".

Related