C++ Standard Library C++ STL Library

C++ <cstdlib> - rand() Function



The C++ <cstdlib> rand() function returns a pseudo-random integral value between 0 and RAND_MAX (0 and RAND_MAX included).

srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1).

Syntax

int rand (void);

Parameters

No parameter is required.

Return Value

Returns pseudo-random integral value between 0 and RAND_MAX.

Example:

In the example below, rand() function is used to generate 20 pseudo-random integral values between 1 and 100.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
 
int main (){
  int rand_num;

  //initialize random seed
  srand (time(NULL));

  //generating 20 random number between 1 and 100
  cout<<"Random numbers in [1, 100]:\n";
  for(int i = 0; i < 20; i++) {
    rand_num = rand() % 100 + 1;
    cout<<rand_num<<" ";
  }

  return 0;
}

One of the possible output of the above code could be:

Random numbers in [1, 100]:
9 17 69 39 73 20 13 43 66 10 92 75 69 65 49 24 55 88 56 61 

Example:

Consider one more example where this function is used to generate 10 pseudo-random values between 0 and 1.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
 
int main (){
  double rand_num;

  //initialize random seed
  srand (time(NULL));

  //generating 10 random number between 0 and 1
  cout<<"Random values in [0, 1]:\n";
  for(int i = 0; i < 10; i++) {
    rand_num = (double) rand() / RAND_MAX;
    cout<<rand_num<<"\n";
  }

  return 0;
}

One of the possible output of the above code could be:

Random values in [0, 1]:
0.514484
0.553147
0.288001
0.626409
0.996425
0.664147
0.64688
0.0778568
0.414238
0.635943

❮ C++ <cstdlib> Library