Generating Random Numbers in C with rand and srand

Generating pseudo-random numbers in the C programming language is a standard task accomplished using the built-in functions rand() and srand(), defined in the <stdlib.h> header. This article covers the standard methodology for initializing the pseudo-random number generator using the system clock via time(), producing raw random values, and scaling those values to fit a custom specified range.

Essential Headers

To generate random numbers using the standard methodology, include both <stdlib.h> and <time.h>:

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

Seeding the Generator with srand()

The rand() function uses an internal mathematical algorithm to produce an identical sequence of numbers each time the program runs unless initialized with a different starting point, known as a seed.

The srand(unsigned int seed) function establishes this initial seed. To produce different output on each execution, pass the current calendar time using time(NULL):

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

This initialization must be called only once during program execution—typically at the beginning of the main() function. Calling srand() inside a loop or repeatedly before calling rand() will reset the generator state, frequently resulting in duplicate numbers if executed within the same second.

Generating Numbers with rand()

Once seeded, calling rand() generates a pseudo-random integer in the range from 0 to RAND_MAX (a macro guaranteed to be at least 32,767).

int raw_value = rand();

Restricting Numbers to a Specific Range

Because raw values span from 0 to RAND_MAX, the standard idiom to map the result into a bounded range [min, max] uses the modulus operator (%):

int random_in_range = (rand() % (max - min + 1)) + min;

For example, to simulate rolling a standard six-sided die (1 to 6):

int die_roll = (rand() % 6) + 1;

Complete Implementation Example

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

int main(void) {
    int min = 10;
    int max = 50;

    // Seed the random number generator once
    srand((unsigned int)time(NULL));

    // Generate and print five pseudo-random numbers between 10 and 50
    for (int i = 0; i < 5; i++) {
        int random_num = (rand() % (max - min + 1)) + min;
        printf("Random Value %d: %d\n", i + 1, random_num);
    }

    return 0;
}

Limitations of rand()

The rand() and srand() functions are intended for general simulations, casual games, and algorithmic testing. They are not cryptographically secure, and the modulo method introduces a slight mathematical bias if (max - min + 1) does not evenly divide RAND_MAX + 1. For security-critical applications or cryptographic uses, platform-specific cryptographic APIs should be utilized instead.