C Standard Library

C <stdlib.h> - srand() Function



The C <stdlib.h> 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 example below, 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 <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main (){
  int rand_num;

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

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

  return 0;
}

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

Random numbers in [1, 100]:
8 44 72 68 80 83 70 14 47 19 70 41 87 82 61 79 62 70 30 74 

Example:

Consider one more example where this function seeds the rand() function which is used to generate 10 pseudo-random values between 0 and 1.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main (){
  double rand_num;

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

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

  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 <stdlib.h> Library