Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


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

For every different seed value used in a call to srand(), the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand() function.

Syntax

void srand (unsigned int seed);

Parameters

seed Specify an integer value to be used as seed value.

Return Value

None.

Example:

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

#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 will be:

Random numbers in [1, 100]:
27 9 83 86 44 80 21 28 39 53 78 78 94 13 79 64 31 15 22 69 

❮ C++ <cstdlib> Library