Problem with rand

0 Darsh Patel · December 28, 2014
I know what rand does i don't know what this code does:

srand(time(NULL));

Please can you help me out.

Post a Reply

Replies

Oldest  Newest  Rating
0 Darsh Patel · December 31, 2014
Thanks
0 Franz Schmidt · December 28, 2014

stackoverflow: http://stackoverflow.com/questions/5620163/use-of-srand-in-c


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/

  • 1

C

107,076 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator