HOME HTML EDITOR C JAVA PHP

C Random Numbers: Generating Stochastic Data

In C, generating random numbers is essential for simulations, games, cryptography, and testing. The standard library <stdlib.h> provides functions to generate pseudo-random numbers—sequences that appear random but are actually determined by a mathematical formula.

1. The rand() Function

The rand() function returns a pseudo-random integer between 0 and RAND_MAX (a constant defined in stdlib.h, usually 32767).

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

int main() {
    int num = rand();
    printf("Random Number: %d\n", num);
    return 0;
}

2. Seeding the Generator (srand)

If you run the code above multiple times, you will notice it produces the same number every time. This is because the generator starts with the same "seed" value by default. To get different numbers every time the program runs, we must "seed" the generator using srand() and the current time.

#include <time.h>

// Seed with current time
srand(time(NULL));
int random_num = rand();

3. Generating Numbers in a Specific Range

To get a number within a specific range (e.g., 1 to 10 or 1 to 100), we use the Modulo Operator (%).

Requirement Formula
Range: 0 to N-1 rand() % N
Range: 1 to N (rand() % N) + 1
Range: Min to Max (rand() % (Max - Min + 1)) + Min

4. Practical Example: Rolling a Die

This example demonstrates how to generate a random number between 1 and 6, simulating a standard six-sided die.

srand(time(NULL));

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

5. Important Considerations

6. Technical Summary

Header <stdlib.h> (and <time.h> for seeding)
Mechanism Linear Congruential Generator (LCG)
Repeatability Fixed seed results in fixed sequences (useful for debugging).
Pro Tip: If you are debugging a complex game or simulation and want to reproduce a specific bug, use a fixed seed (e.g., srand(42);) instead of time(NULL). This ensures the "random" sequence is the same every time you run the test!