C Standard Library

C <stdlib.h> - rand() Function



The C <stdlib.h> 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 <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 could be:

Random numbers in [1, 100]:
95 94 1 62 45 74 53 47 94 63 54 78 41 10 54 52 23 96 48 13 

❮ C <stdlib.h> Library

5