![]() |
![]() |
![]() |
C++ Reference: rand()
rand()
Declaration
int rand();
Description
Returns a pseudo-random sequence of numbers in the range 0 to RAND_MAX with successive calls. The pseudo-random number generator is seeded with srand().
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:
![]() |
![]() |
![]() |
| Home | | | Reference | | | Play Games! | | | Blog | | | Forum | | | Site Map | | | Contact Us |





