Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 135 Β· Standard Library

Random Numbers

Generate random numbers in C with rand and srand, seed them properly, pick values in a range without bias, shuffle arrays with Fisher-Yates and write a better generator.

Games roll dice, simulations sample noise, tests generate random input, and programs shuffle playlists. C's standard library offers one simple tool for all of this: rand() from <stdlib.h>, together with srand() to choose where its sequence starts. They're easy to use, but also easy to use wrong: the textbook rand() % 6 + 1 is subtly biased, forgetting to seed gives the same "random" numbers every run, and rand must never be used for passwords or keys.

This lesson shows how rand really works, how to seed it, how to get integers and floating-point numbers in a range correctly, how to shuffle an array, and when (and how) to replace rand with a better generator.

rand and srand

rand() returns a pseudo-random integer between 0 and RAND_MAX inclusive. RAND_MAX is at least 32767; with glibc on Linux it's 2147483647, while Microsoft's C library still uses 32767. The numbers come from a deterministic formula: each call transforms a hidden internal state into the next number. Start from the same state, and you get exactly the same sequence.

srand(seed) sets that starting state. If you never call it, the program behaves as if it had called srand(1).

C The same seed gives the same sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first two rows are identical (no seed means seed 1), and so are the last two. The actual numbers depend on the C library; the ones you see are glibc's. That repeatability is a feature: a simulation or a test that fails with seed 2026 can be rerun with seed 2026 and fail the same way.

Note: Each rand() call is stored in a variable before printing on purpose. Writing printf("%d %d", rand(), rand()) doesn't guarantee which call happens first: C leaves the evaluation order of function arguments unspecified, and GCC on x86-64 often evaluates them right to left.

Seeding with the time

To get a different sequence on every run, seed with something that changes, traditionally the current time:

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

int main(void)
{
    srand((unsigned)time(NULL));     /* once, at the start of the program */
    /* ... */
}

Two rules go with this:

  • Seed once. Calling srand(time(NULL)) before every rand() restarts the sequence each time, and because time only changes once per second, you'd get the same "random" number again and again.
  • Time is a weak seed. Two programs started in the same second get identical sequences, and anyone who knows roughly when the program started can guess the seed. For better seeds, mix in more data: the nanoseconds from timespec_get, the process ID, or bytes from the operating system's random source (see the end of this lesson).

Random integers in a range

The classic way to get a number from min to max is min + rand() % (max - min + 1). It's short and it always lands in the range, but it's biased whenever the range size doesn't divide RAND_MAX + 1 evenly.

Here's why. Imagine RAND_MAX were 9, so rand() returns 0–9 (ten values), and you want a die roll 0–5 with rand() % 6. Values 0–5 map to 0–5 and values 6–9 map to 0–3. So 0, 1, 2 and 3 come up twice as often as 4 and 5. With glibc's huge RAND_MAX the bias for a die is tiny (0 and 1 are favored by about one part in 358 million), but with Microsoft's 32767 and a range like 0–9999, the low numbers 0–2767 appear about 33% more often than the rest. That's real, measurable bias.

The fix is rejection sampling: throw away the few values at the top that don't fill a complete block, and draw again.

C Biased modulo versus rejection sampling

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With a 32768-value generator, the modulo version returns a number below 2768 about 33.8% of the time instead of the fair 27.68%, while the rejection version stays at about 27.7%. The rejection loop rarely repeats: in the worst case it rejects less than half the values, and for small ranges almost none.

Here's the general helper to copy into your own programs, using the real RAND_MAX:

C
/* Returns a uniformly distributed int in [min, max]. Requires max - min < RAND_MAX. */
int random_int(int min, int max)
{
    unsigned span = (unsigned)(max - min) + 1u;
    unsigned limit = ((unsigned)RAND_MAX + 1u) - ((unsigned)RAND_MAX + 1u) % span;
    unsigned r;
    do {
        r = (unsigned)rand();
    } while (r >= limit);
    return min + (int)(r % span);
}

Warning: Don't "fix" the bias with rand() / (RAND_MAX / span) or floating-point scaling like (int)(rand() / (RAND_MAX + 1.0) * span). Both look smoother, but they still map an uneven number of inputs to each output; they only move the bias around. Rejection is the correct solution.

Random floating-point numbers

For a double in [0, 1), divide by RAND_MAX + 1.0 (the .0 makes it floating-point division and avoids overflow). Scale and shift for other ranges. This is fine for simulations and games; the only limitation is that with glibc you get at most 231 different values, far fewer than a double can hold.

C Estimating pi with random points

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

This is the Monte Carlo method: answer a question by sampling at random. A million darts estimate Ο€ to two or three decimal places (this seed gives 3.1436). The error shrinks only with the square root of the sample count, so each extra correct digit costs a hundred times more darts. Change the seed to see the estimate move a little.

Shuffling with Fisher–Yates

To put an array in random order, every arrangement should be equally likely. The Fisher–Yates shuffle (also called the Knuth shuffle) does that in one pass: walk from the last element down to the second, and swap each element with a randomly chosen one at or before its position.

C Shuffling a deck of cards

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The index j must be chosen from 0 to i inclusive. Two tempting variations are wrong: choosing j from the whole array every time (random_int(0, count - 1)) produces some orders more often than others, and choosing from 0 to i - 1 (Sattolo's algorithm) can never leave an element in place. The counting loop is a quick sanity check you can apply to any shuffle.

The same idea gives you random sampling without repeats: shuffle, then take the first k elements. You can even stop the loop after k swaps if you run it from the front.

Better generators

rand is fine for small games and exercises, but it has real limitations:

  • Its quality isn't specified. Historic implementations had famously poor low bits (alternating odd/even), and Microsoft's only gives 15 bits per call.
  • It has a single hidden global state, so it isn't thread-safe and you can't have two independent streams.
  • It's predictable and must never be used for security.

For simulations and games, a small, well-tested generator that you control is a common upgrade. SplitMix64 and the xoshiro and PCG families are popular choices: fast, statistically strong, and with a state you pass around explicitly. Here's SplitMix64, which is just a few lines:

C A tiny 64-bit generator: SplitMix64

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Streams a and b produce identical numbers because they have the same seed, and c, seeded with 43, is completely different. Each stream is an ordinary struct, so different threads or different parts of a simulation can have their own. The output is the same on every platform, which rand can't promise. (The three rng64_next calls in one printf are on three different generators, so their evaluation order doesn't matter here.)

Random numbers for security

Session tokens, passwords, keys and anything an attacker might try to predict need a cryptographically secure source, which only the operating system provides. None of these are in standard C:

C
/* Linux (glibc 2.25+) */
#include <sys/random.h>
unsigned char key[32];
if (getrandom(key, sizeof key, 0) != (ssize_t)sizeof key) { /* handle error */ }

/* macOS, the BSDs, and glibc 2.36+ */
uint32_t token = arc4random();
uint32_t die = arc4random_uniform(6) + 1;   /* unbiased range */

/* Windows: BCryptGenRandom from <bcrypt.h> */

Reading from /dev/urandom with fread also works on Unix-like systems. These sources are slower than rand, so they're also commonly used just to seed a fast generator.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. A program calls rand() three times without ever calling srand. What happens when you run it twice?

    rand behaves as if seeded with 1 when srand was never called, so the sequence is the same in every run.
  2. 2. Why is calling srand(time(NULL)) before every rand() call a bug?

    time changes once per second, and each srand restarts the sequence. Seed once at program start.
  3. 3. With RAND_MAX = 9 (values 0 to 9), which results of rand() % 4 are more likely than the others?

    Ten values split into blocks of four (0-3, 4-7) plus a partial block (8, 9). The partial block maps to 0 and 1, so they occur 3 times out of 10 and 2 and 3 only twice.
  4. 4. In Fisher-Yates, element i is swapped with a random index j. Which range must j come from?

    Choosing from 0 to i inclusive makes every permutation equally likely. Using the whole array is biased, and excluding i (Sattolo's algorithm) never leaves an element in place.
  5. 5. Which is appropriate for generating a password-reset token?

    rand and fast generators are predictable once the seed or a few outputs are known. Security needs the OS's cryptographically secure generator.

Summary

  • rand() returns pseudo-random integers from 0 to RAND_MAX (at least 32767; 2147483647 with glibc); srand(seed) sets the start of the sequence, and no seed means seed 1.
  • Seed once, for example with srand((unsigned)time(NULL)); reuse a fixed seed when you need reproducible runs.
  • rand() % n is biased unless n divides RAND_MAX + 1; use rejection sampling for a fair range.
  • rand() / (RAND_MAX + 1.0) gives a double in [0, 1); scale it for other ranges.
  • Shuffle with Fisher–Yates, choosing j from 0 to i inclusive.
  • For better quality, multiple streams or portable sequences, use a small generator like SplitMix64, xoshiro or PCG; for anything security-related, use the OS (getrandom, arc4random, BCryptGenRandom).

Next: qsort and bsearch, where you'll sort numbers, strings and structs with the standard library and search sorted arrays.