C++ cstdlib srand() Function
Example
Use the current time as the seed, to get different random numbers each time the program runs:
srand(time(0));
for (int i = 0; i < 3; i++) {
cout << rand() % 100 + 1 << "\n";
}
Definition and Usage
The srand() function sets the starting value (the seed) for rand(). The same seed always gives the same random numbers.
To get different numbers each time the program runs, use the current time as the seed, like srand(time(0)). The time() function is in the <ctime> library.
The srand function is defined in the <cstdlib> header file.
Note: The output is random, so it is different each time you run the program.
Tip: Call srand() only once, at the start of the program. Do not call it again before each call to rand().
Syntax
void srand(unsigned int seed);
Parameter Values
| Parameter | Description |
|---|---|
| seed | Required. The starting value for rand(). |
Technical Details
| Returns: | Nothing. |
|---|