Lesson 29: 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 an unpredictable value with no regular pattern. You'll find them everywhere: enemy spawn positions in games, dice simulations, cryptographic keys, and more.
In C, you generate pseudo-random numbers with the rand() function from stdlib.h. They're called "pseudo" because a mathematical formula produces them internally, so they aren't truly random — but for everyday use, they're good enough.

Required headers

#include <stdlib.h>   // rand(), srand()
#include <time.h>     // time() - for the seed
Use rand for exercises, not cryptography. It is not suitable for passwords, security tokens, or other values that must be unpredictable to an attacker.

rand() and srand()

rand() returns 0 〜 RAND_MAX (often 2147483647). Without seeding, it produces the same sequence each run.

Set the seed

srand(seed) sets the seed and selects a pseudorandom sequence. 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 with the current time (which changes between runs) 

    for (int i = 0; i < 5; i++) {
        printf("%d\n", rand());
    }
    return 0;
}
What happens without srand()?
Press a button to compare →

Generate random numbers in a range

rand() returns a large integer, so use the remainder operator % to restrict the range.
// Random value from 0 through 9 
int r = rand() % 10;

// Random value from 1 through 6 (a die) 
int dice = rand() % 6 + 1;

// Random value from min through max 
int val = rand() % (max - min + 1) + min;
Range formulas
Goal Code
0 〜 N-1rand() % N
1 〜 Nrand() % N + 1
min 〜 maxrand() % (max - min + 1) + min

Dice simulator

?

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("Computer: %s\n" , hands[cpu]);
    return 0;
}
Rock-paper-scissors simulator

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;
}
Shuffle demo

Visualize the random distribution

rand() % N: inspect the resulting histogram. As the trial count grows, the frequencies tend to become more even.

Try it yourself

Write a program using random numbers. This editor supports rand(), srand(), and time().
💡 More things to try

← Previous lesson
Lesson 28: Elementary Functions (math.h)
Next lesson →
Lesson 30: Prototype & Macro

Related lessons

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

Review 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 narrow 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 for the random number generator. Since the same seed always produces the same sequence, time(NULL) is a common choice.

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

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

rand() % 6 returns 0 through 5, so adding 1 gives you 1 through 6. rand() % 7 would return 0 through 6.

Share this article
Share on X Share on Facebook