C Language | Advanced Features | Random Numbers - rand(), srand()

The C standard library provides functions for generating pseudorandom numbers.

Getting Random Values

rand() is declared in stdlib.h.

int rand(void);

It returns an integer from 0 through RAND_MAX. The values are pseudorandom: the same initial seed produces the same sequence.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int iCount;
  printf("RAND_MAX = %d\n", RAND_MAX);
  for (iCount = 0; iCount < 10; iCount++)
    printf("random %d = %d\n", iCount, rand());
  return 0;
}

Use srand() to set the seed.

void srand(unsigned int seed);

The current time is commonly used when a different sequence is desired for each run.

#include <stdlib.h>
#include <time.h>

srand((unsigned int)time(NULL));

For a value in the range from 0.0 up to but not including 1.0, divide by RAND_MAX + 1.0.

#undef random
#define random() ((double)rand() / ((double)RAND_MAX + 1.0))

rand() is suitable for simulations and simple games, but not for cryptographic purposes.