Home
menubar
rss_feed

Previous Reference C++ Reference <cstdlib> Next Reference




C++ Reference: srand()





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:








Previous Reference C++ Reference <cstdlib> Next Reference




Home | Reference | Play Games! | Blog | Forum | Site Map | Contact Us


shadow bottom image