srand() function with time(0) function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

srand() function with time(0) function

Can anyone explain this statement from the C++ Tutorial? #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main () { srand(time(0)); for (int x = 1; x <= 10; x++) { cout << 1 + (rand() % 6) << endl; } } "time(0) will return the current second count, prompting the srand() function to set a different seed for the rand() function each time the program runs" Does this mean that for every iteration the value gets changed as the time is changed? Or Does this mean that every time when I run the code, the values will be changed?

4th Aug 2017, 3:39 PM
Kalliath Abdul Rasheed Shamil
Kalliath Abdul Rasheed Shamil - avatar
2 Answers
+ 9
Imagine you have an RNG algorithm: static x = 5; // some codes value = x + 7 * (8%x) - 20; x++; So you get different values every time you call the block of code. However, when you restart your program, you realise your values are the same as the previous run! This is because your x value is always 5 initially. In order to get a different value for each time you run your program, you need to change the value of x to something else, not statically 5. Hence, we say that seeding is required. Let's use time(0) static x = time(0) // some codes value = x + 7 * (8%x) - 20; x++; time(0) returns the system time in seconds since 1/1/1970. This means that the value is constant changing, and will be different the next time you run your program. Try doing: std::cout << time(0); and see what happens. Also, try doing: for (int i = 0; i < 10; i++) { std::cout << rand() << " "; } without using srand().
4th Aug 2017, 4:24 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
The seed will stay the same in this case, and it will only change when you run the code again
4th Aug 2017, 3:51 PM
aklex
aklex - avatar