+ 5
Computers canât actually generate random numbers, so they use âpseudo randomâ. When you call srand, you set the seed to the number you use as a parameter. By making this seed unpredictable, like by calling time(0), the numbers generated will seem random.
You can call rand without srand, but there will be the same pattern of numbers every time the code runs.
#include <iostream>
#include <ctime> //time(0)
#include <cstdlib>
using namespace std;
int main() {
srand(time(0));
for (int a = 0; a < 5; a++) {
cout << rand() << endl;
}
}
This outputs 5 random numbers. You only need to call srand once at the beginning of the program no matter how many times you call rand.