+ 2

Can u pls. Clarify srand() in more detail ??

how srand() works

2nd Jan 2017, 4:13 PM
neha gupta
neha gupta - avatar
2 Answers
+ 17
rand() generates a random no while srand() provides a seed value for rand() and for that particular value it generates a random no. srand(x) will give rand() a seed of 'x' and hence for same value of x, same no will be generated. So in general we use srand(time(0)) which analyzes the time and by every passing second gives a different seed value to rand() function. So whenever you use that, you get different random numbers.
2nd Jan 2017, 4:22 PM
Frost
Frost - avatar
+ 6
Well, first of all know that, A MACHINE CANNOT PRODUCE A RANDOM NUMBER. when you call the rand function, it just performs a bunch of complex calculations on a number (called a *seed*) to produce a number that seems random. however, the problem is, the rand function always uses the same seed for calculations, so it produces the same set of numbers no matter how many times you run it. to give it a different seed, we use the srand function. usually we pass in the time to the srand function, so that it uses a different seed each time it calculates a random number (as time is different every time).
2nd Jan 2017, 4:28 PM
Nikunj Arora
Nikunj Arora - avatar