Open In App

rand() and srand() in C++

Last Updated : 19 May, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The rand() in C++ is a built-in function that is used to generate a series of random numbers. It will generate random numbers in the range [0, RAND_MAX) where RAND_MAX is a constant whose default value may vary but is granted to be at least 32767.

Syntax

The std::rand() function is defined inside the <cstdlib> and <stdlib.h> header file.

C++
rand();

This function does not take any parameters and returns a pseudo-random number in the range of [0, RAND_MAX).

Example of rand()

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    for (int i = 0; i < 3; i++)
    
        // Generate random numbers
        cout << rand() << endl;
    return 0;
}

Output
1804289383
846930886
1681692777

srand()

The random number generated by rand() function is generated using an algorithm that gives a series of non-related numbers by taking 1 as the starting point or seed. Due to this, the random number series will aways be same for different function calls. To resolve this problem, we use srand() function.

The srand() function changes the "seed" or the starting point of the algorithm. A seed is an integer used to initialize the random number generator.

Syntax

C++
srand(seed);

where, seed is an integer value for random number generator using rand() function. This function does not return any value.

Example

For the seed, we mostly use the current time in the srand() function to ensure a different sequence of random numbers.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {

    // Use current time as seed for random generator
    srand(time(0));
    for (int i = 0; i < 3; i++)
        cout << rand() << endl;
    return 0;
}

Output
582797172
409020522
244217599

Random Numbers in Modern C++

The rand() and srand() functions are inherited by C++ from C language. They use the deterministic algorithms to find the next random number. It means that it generates the same sequence of numbers every time for the same seed.

To provide high quality randomness, C++ 11 introduced <random> library with more sophisticated random number generates like mt19937 engine. This engine also uses deterministic sequence generator but with more sophistication and uniform distribution. When seeded with random_device (which provides true non-deterministic random seed value if OS supports), it is almost guaranteed to be more random than rand().

rand() function is mainly used to generate random numbers in our program which can be used in the following applications:



rand() in C++
Visit Course explore course icon
Article Tags :
Practice Tags :

Similar Reads