C Standard Libraries C++

srand()

Declaration

void srand(unsigned int uiSeed);

Description

This function seeds the pseudo-random number generator used by the rand() function.

Example

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    using namespace std;

    time_t qTime;
    time(&qTime);

    // Use a varying seed, like time, to generate new sequences.
    srand(qTime);
    cout << "A varying sequence of random numbers:" << endl;
    for (unsigned int uiIndex = 0; uiIndex < 10; ++uiIndex) {
        cout << "  " << rand();
    }
    cout << endl;

    // Use a constant with srand to generate the same sequence.
    srand(2);
    cout << "A fixed sequence of random numbers:" << endl;
    for (unsigned int uiIndex = 0; uiIndex < 10; ++uiIndex) {
        cout << "  " << rand();
    }
    cout << endl;

    cout << "The generated range is 0 to " << RAND_MAX << endl;

    return 0;
}

Output

srand() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.