🇯🇵 日本語 | 🇺🇸 English
Advertisement

Lesson 17: Random Number Generation

How to use rand() and srand() in C. Ranges, seeds, and applications illustrated.

📖 What to learn on this page
✅ Must-know essentials
  • Seed with srand((unsigned)time(NULL));
  • Get a number with rand()
  • rand() % N for 0 to N-1
⭐ Read if you have time
  • RAND_MAX and modulo bias
  • Better PRNGs (arc4random, Mersenne Twister)
  • Fixed seed for reproducibility

What is a Random Number?

A random number is a number with no regular pattern, unpredictable. They appear everywhere: the spawn position of game enemies, dice simulations, cryptographic keys, and more.
In C, you generate pseudo-random numbers with the rand() function in stdlib.h. They are called "pseudo" because internally they are produced by a mathematical formula and are not truly random — but for ordinary use they are good enough.

Required headers

#include <stdlib.h>   // rand(), srand()
#include <time.h>     // time() - for the seed

rand() and srand()

rand() returns an integer in the range 0 to RAND_MAX (typically 2147483647). But if you use it as-is, you get the same sequence every time.

Setting the seed

Calling srand(seed) sets the random number "seed" and produces a different sequence from that seed. Call it once, at the start of the program.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    srand(time(NULL));  // seed from current time (different every run)

    for (int i = 0; i < 5; i++) {
        printf("%d\n", rand());
    }
    return 0;
}
If you forget srand(): the output will be exactly the same every run because the default seed is 1.

Generating Numbers in a Range

rand() returns very large numbers, so use the modulo operator % to narrow the range.
// 0 to 9
int r = rand() % 10;

// 1 to 6 (a die)
int dice = rand() % 6 + 1;

// min to max
int val = rand() % (max - min + 1) + min;
Formula summary
GoalCode
0 to N-1rand() % N
1 to Nrand() % N + 1
min to maxrand() % (max - min + 1) + min

Application: Rock-Paper-Scissors

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

int main(void) {
    char *hands[] = {"Rock", "Scissors", "Paper"};
    srand(time(NULL));
    int cpu = rand() % 3;  // 0:Rock 1:Scissors 2:Paper

    printf("CPU: %s\n", hands[cpu]);
    return 0;
}

Application: Array Shuffle (Fisher-Yates)

// Fisher-Yates shuffle
for (int i = n - 1; i > 0; i--) {
    int j = rand() % (i + 1);
    // swap a[i] and a[j]
    int tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
}

Visualizing the Distribution

Is the output of rand() % N really uniformly distributed? Check it with a histogram. The more trials you run, the more even it becomes.
A good random generator makes every outcome equally likely. Short runs can look uneven, but over thousands of trials the counts approach N/trials for each bucket.

Try It Yourself

Try writing programs that use random numbers. You can use rand(), srand(), and time().
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

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

    // Roll a die 10 times
    for (int i = 0; i < 10; i++) {
        int dice = rand() % 6 + 1;
        printf("Roll %d: %d\n", i + 1, dice);
    }
    return 0;
}
💡 Try these ideas too
Advertisement
← Previous lesson
Lesson 16: Math Functions
Next lesson →
Lesson 18: Arrays

Related lessons

Loops, Arrays, Strings
Lesson 16: Elementary Functions (math.h)
The C math.h library. sqrt, sin, cos, pow and other math functions.

Quiz

Check your understanding!

Q1. What is the range of the rand() return value?

0 to 99
0 to RAND_MAX
1 to 100

rand() returns an integer between 0 and RAND_MAX (usually at least 32767). Use the % operator to restrict it to a specific range.

Q2. What does srand() do?

Generates a random number
Sets the seed of the random generator
Sorts random numbers

srand() sets the seed of the random number generator. The same seed produces the same sequence, so time(NULL) is typically used.

Q3. Which expression gives a die roll of 1 to 6?

rand() % 6
rand() % 6 + 1
rand() % 7

rand() % 6 returns 0 to 5, so add 1 to get 1 to 6. rand() % 7 would return 0 to 6.

Share this article
Share on X Share on Facebook