Reading history

Random Numbers in C: rand, srand, Ranges and Shuffling

6 min read 0 views

Generate random numbers in C: rand and srand, unbiased ranges, fractions, a portable xorshift generator, Fisher-Yates shuffle and Monte Carlo pi.

Games roll dice, quizzes shuffle questions, simulations model traffic, and lucky draws pick winners. All of them need random numbers. C provides rand() and srand() in <stdlib.h>, but using them well takes some care: how to get a number in a range without bias, when to seed, and how to make results repeatable. This lesson covers all of that, then shuffles an array and estimates π with random points.

In this lesson you will learn

  • How rand(), RAND_MAX and srand() work
  • Random integers in a range, without modulo bias
  • Random fractions between 0 and 1
  • Writing a small generator that gives the same results on every system
  • Fisher–Yates shuffle and a Monte Carlo estimate of π

You should know loops, arrays and the time.h header.

rand, srand and Ranges

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

/* Random integer in [lo, hi] without the worst modulo bias */
int rand_range(int lo, int hi) {
    int span = hi - lo + 1;
    int limit = RAND_MAX - (RAND_MAX % span);   /* largest multiple of span */
    int r;
    do {
        r = rand();
    } while (r >= limit);                        /* throw away the uneven tail */
    return lo + r % span;
}

int main(void) {
    printf("RAND_MAX on this system: %d\n", RAND_MAX);

    /* A fixed seed gives the same sequence every run: handy for testing */
    srand(42);
    int first[5];
    for (int i = 0; i < 5; i++) first[i] = rand_range(1, 6);
    srand(42);
    int same = 1;
    for (int i = 0; i < 5; i++) same &= (rand_range(1, 6) == first[i]);
    printf("same seed, same dice rolls: %s\n", same ? "yes" : "no");

    /* Roll a die 60,000 times: each face should appear about 10,000 times */
    int count[7] = {0};
    for (int i = 0; i < 60000; i++) count[rand_range(1, 6)]++;
    int fair = 1;
    for (int f = 1; f <= 6; f++)
        if (count[f] < 9500 || count[f] > 10500) fair = 0;
    printf("each face within 5%% of 10,000: %s\n", fair ? "yes" : "no");

    /* A random double in [0, 1) */
    double x = rand() / (RAND_MAX + 1.0);
    printf("random fraction in range: %s\n", (x >= 0.0 && x < 1.0) ? "yes" : "no");

    /* For a different sequence each run, seed from the clock (once!) */
    srand((unsigned)time(NULL));
    printf("seeded from the clock\n");
    return 0;
}

Output

RAND_MAX on this system: 2147483647
same seed, same dice rolls: yes
each face within 5% of 10,000: yes
random fraction in range: yes
seeded from the clock
  • rand() returns a whole number from 0 to RAND_MAX. The C standard only promises that RAND_MAX is at least 32,767; on this system it is 2,147,483,647, but yours may differ.
  • The numbers are pseudo-random: a formula produces them from a starting value called the seed. srand(42) sets the seed, and the same seed always gives the same sequence, which is very useful when testing or debugging.
  • rand() % 6 is slightly unfair whenever RAND_MAX + 1 is not a multiple of 6, because a few low numbers get one extra chance. rand_range rejects values in that uneven tail and draws again, so each face is equally likely. Over 60,000 rolls, every face came up within 5% of the expected 10,000.
  • rand() / (RAND_MAX + 1.0) gives a fraction from 0 up to, but never reaching, 1. The 1.0 forces floating-point division.
  • srand((unsigned)time(NULL)) seeds from the current time, so each run is different. Call it once at the start of the program, never before every rand(); calls within the same second would get the same seed and the same numbers.

A Portable Generator, Shuffling and π

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

/* xorshift32: a tiny generator that gives the same numbers on every system */
static uint32_t state = 2026;

uint32_t next_u32(void) {
    uint32_t x = state;
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    return state = x;
}

int pick(int n) { return (int)(next_u32() % (uint32_t)n); }   /* 0 .. n-1 */

/* Fisher-Yates shuffle: every order is equally likely */
void shuffle(int *a, int n) {
    for (int i = n - 1; i > 0; i--) {
        int j = pick(i + 1);          /* 0 .. i */
        int t = a[i]; a[i] = a[j]; a[j] = t;
    }
}

int main(void) {
    int cards[10];
    for (int i = 0; i < 10; i++) cards[i] = i + 1;
    shuffle(cards, 10);
    printf("shuffled: ");
    for (int i = 0; i < 10; i++) printf("%d ", cards[i]);
    printf("\n");

    const char *names[] = {"Rafi", "Nadia", "Sumon", "Mim", "Arif"};
    printf("lucky draw winner: %s\n", names[pick(5)]);

    /* Estimate pi: fraction of random points inside a quarter circle */
    int inside = 0, total = 1000000;
    for (int i = 0; i < total; i++) {
        double x = next_u32() / 4294967296.0, y = next_u32() / 4294967296.0;
        if (x * x + y * y < 1.0) inside++;
    }
    printf("pi is roughly %.2f\n", 4.0 * inside / total);
    return 0;
}

Output

shuffled: 5 6 8 9 1 7 2 10 4 3 
lucky draw winner: Sumon
pi is roughly 3.14
  • Different C libraries use different formulas for rand(), so the same seed gives different numbers on Windows and Linux. xorshift32 is a tiny, well-known generator built from three shifts and XORs. Written yourself, it produces exactly the same sequence everywhere, which matters for games that replay a level or tests that compare outputs.
  • The state is a uint32_t from <stdint.h>, so it is exactly 32 bits on every system and overflow simply wraps around.
  • The Fisher–Yates shuffle walks from the end of the array, swapping each position with a random position at or before it. Every possible order is equally likely. Swapping each item with any random position, a common mistake, makes some orders more likely than others.
  • The π estimate drops one million random points in a 1 × 1 square. The fraction that land inside the quarter circle x² + y² < 1 is close to π / 4, so multiplying by 4 gives about 3.14. Using randomness to approximate an answer like this is called a Monte Carlo method.

Random Number Recipes

GoalCode
Integer from lo to hirand_range(lo, hi) (rejection, as above)
Fraction in [0, 1)rand() / (RAND_MAX + 1.0)
True or false with 30% chancerand() / (RAND_MAX + 1.0) < 0.3
Repeatable runssrand(fixed_number) or your own generator
Different runssrand(time(NULL)) once at start

Common Mistakes

  1. Calling srand inside a loop, which keeps restarting the sequence.
  2. Using rand() for passwords, tokens or security. It is predictable. Use the operating system’s secure source, such as getrandom on Linux or BCryptGenRandom on Windows.
  3. Writing rand() / RAND_MAX, which is integer division and almost always gives 0.
  4. Using rand() % n for large n, where the bias becomes noticeable.

Practice Exercises

Exercise 1. Simulate tossing a coin 1,000 times with rand_range(0, 1) and print how many heads came up.

Show answer
int heads = 0;
for (int i = 0; i < 1000; i++)
    heads += rand_range(0, 1);
printf("heads: %d\n", heads);   /* close to 500 */

Exercise 2. Generate a 6-digit one-time code for a practice app, allowing leading zeros.

Show answer
int code = pick(1000000);   /* 0 .. 999999, from the xorshift generator */
printf("%06d\n", code);    /* %06d pads with zeros, e.g. 004271 */

pick is used because the range is larger than the smallest allowed RAND_MAX (32,767); rand_range only works for spans up to RAND_MAX. For a real login system, use a cryptographically secure source instead.

Frequently Asked Questions

Are computer random numbers really random?

Not the ones from rand(). They come from a formula, so they only look random. Operating systems also collect unpredictable events, such as hardware timing noise, to produce secure random numbers for cryptography.

Why do I get the same numbers every time I run my program?

Without srand, the seed is 1 by default, so the sequence is always the same. Seed once from the clock if you want different results on each run.

Summary

  • rand() gives 0 to RAND_MAX; srand sets the starting seed.
  • Use rejection to get unbiased numbers in a range.
  • Seed once; use a fixed seed or your own generator for repeatable results.
  • Fisher–Yates shuffles fairly; never use rand() for security.

Next: assert and Debugging Techniques in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *