C Random Number Generation: rand, srand, Seeds, and Better Randomness

C provides basic pseudo-random number generation through the stdlib.h header. The rand and srand functions are commonly used for simulations, games, testing, randomized algorithms, and other applications where a simple sequence of pseudo-random values is sufficient.

What is a Random Number?

A computer typically generates pseudo-random numbers rather than truly random numbers. A pseudo-random generator produces a deterministic sequence that appears random but is ultimately based on an internal algorithm and an initial seed.

Using rand in C

The rand function returns a pseudo-random integer between 0 and RAND_MAX, inclusive.

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

int main(void)
{
    int value = rand();

    printf("Random value: %d\n", value);

    return 0;
}

Generating Multiple Random Numbers

Calling rand repeatedly produces successive values from the generator's current sequence.

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

int main(void)
{
    for (int i = 0; i < 5; i++)
    {
        printf("%d\n", rand());
    }

    return 0;
}

Why Use srand?

srand initializes the pseudo-random number generator with a seed. Using the same seed produces the same sequence on a given implementation.

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

int main(void)
{
    srand(12345);

    for (int i = 0; i < 5; i++)
    {
        printf("%d\n", rand());
    }

    return 0;
}

Using the Current Time as a Seed

A common traditional technique is to seed rand with the current calendar time so that separate program runs are less likely to begin with the same sequence.

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

int main(void)
{
    srand((unsigned)time(NULL));

    printf("Random value: %d\n", rand());

    return 0;
}

Generating a Random Number in a Range

The expression rand() % n is often used to produce a value from 0 through n - 1. It is simple, but it can introduce modulo bias when RAND_MAX does not align well with the requested range.

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

int main(void)
{
    srand((unsigned)time(NULL));

    int value = rand() % 10;

    printf("Value: %d\n", value);

    return 0;
}

Generating Numbers Between Two Values

For a small non-security-sensitive program, a common pattern is to map a generated value into a desired interval.

C
int min = 10;
int max = 50;

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

printf("Random value: %d\n", value);

Generating Random Floating-Point Values

A random integer can be normalized to a floating-point value between 0 and 1. The exact statistical quality depends on the implementation of rand.

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

int main(void)
{
    double value = (double)rand() / (double)RAND_MAX;

    printf("Random value: %.6f\n", value);

    return 0;
}

Generating a Random Floating-Point Range

The normalized value can be scaled to a desired floating-point interval.

C
double min = 5.0;
double max = 15.0;

double value = min +
    ((double)rand() / (double)RAND_MAX) * (max - min);

printf("%.3f\n", value);

Understanding RAND_MAX

RAND_MAX is a macro defined by the C standard library. It specifies the maximum value that rand can return on the implementation.

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

int main(void)
{
    printf("RAND_MAX: %d\n", RAND_MAX);
    return 0;
}

Reproducible Random Sequences

Using a fixed seed is useful when testing simulations or debugging randomized algorithms because the same pseudo-random sequence can be reproduced.

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

void generate(void)
{
    for (int i = 0; i < 5; i++)
    {
        printf("%d ", rand());
    }

    printf("\n");
}

int main(void)
{
    srand(42);
    generate();

    srand(42);
    generate();

    return 0;
}

Random Dice Roll

A simple dice simulation can generate an integer from 1 through 6.

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

int main(void)
{
    srand((unsigned)time(NULL));

    int dice = 1 + rand() % 6;

    printf("You rolled: %d\n", dice);

    return 0;
}

Random Boolean Values

A random integer can be mapped to a Boolean result for simple simulations.

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

int main(void)
{
    bool result = (rand() % 2) == 1;

    printf("Result: %s\n", result ? "true" : "false");

    return 0;
}

Avoiding Repeated Seeding

Normally, seed the generator once near program startup rather than repeatedly before every call to rand. Re-seeding too frequently, especially with a low-resolution clock, can cause repeated sequences.

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

int main(void)
{
    srand((unsigned)time(NULL));

    for (int i = 0; i < 5; i++)
    {
        printf("%d\n", rand());
    }

    return 0;
}

Modulo Bias

Using rand() % n does not always produce perfectly uniform results. If the number of possible rand values is not evenly divisible by n, some outcomes occur slightly more often than others.

For casual applications this may be acceptable, but applications requiring statistically uniform samples should use a better range-reduction technique or a stronger random-number facility.

When rand is Not Enough

The standard rand function is intended for basic pseudo-random number generation. Its quality, period, and statistical characteristics are implementation-dependent and may not be suitable for demanding simulations, cryptographic applications, or security-sensitive token generation.

Security-Sensitive Randomness

Do not use rand and srand to generate passwords, authentication tokens, encryption keys, session secrets, or other security-sensitive values. Such applications require a cryptographically secure random source provided by the operating system or an appropriate security library.

rand vs srand

Function / MacroPurpose
rand()Generates the next pseudo-random integer
srand(seed)Initializes the pseudo-random generator
RAND_MAXMaximum value returned by rand()
time(NULL)Can provide a changing calendar-time seed

Common Mistakes

  • Forgetting to seed when a different sequence between runs is desired
  • Seeding before every call to rand
  • Assuming rand produces cryptographically secure randomness
  • Assuming rand has the same sequence on every C implementation
  • Ignoring modulo bias for applications that require uniform sampling
  • Using rand for passwords, tokens, keys, or other security-sensitive values

Best Practices

  • Seed the generator once when appropriate
  • Use a fixed seed when reproducibility is useful for testing
  • Use range reduction carefully when statistical uniformity matters
  • Keep random generation separate from application logic
  • Use operating-system or library facilities designed for secure randomness when security matters
  • Document whether randomness is intended for simulation or security

Real-World Applications

  • Simple games
  • Simulation programs
  • Randomized testing
  • Sample data generation
  • Educational programs
  • Non-security-sensitive randomized algorithms

Practice Exercises

  • Generate ten random integers
  • Simulate rolling a six-sided die
  • Generate a random number between 1 and 100
  • Create a coin-flip simulation
  • Generate random floating-point values between 0 and 1
  • Build a simple number-guessing game
  • Run a simulation using a fixed seed and compare the results

Conclusion

C's rand and srand functions provide a simple interface for pseudo-random number generation. Understanding seeds, RAND_MAX, range mapping, reproducibility, and modulo bias helps you use these functions correctly for basic applications while recognizing when a stronger random-number source is necessary.

Note: Note: rand is not a cryptographically secure random-number generator. For security-sensitive applications, use a cryptographically secure source supplied by the operating system or a suitable security library.