Course contentsShow
← C
Lesson 883 of 1,21912. The Standard LibraryFree lesson

Generating pseudo-random numbers with `rand`

Generating pseudo-random numbers with rand

What you'll learn: How to use the rand() function to generate unpredictable integers for games, simulations, or testing.

The roll of the digital dice

Computers are designed to be logical and predictable. If you ask a computer to do the same task twice, you expect the exact same result. However, when writing a game or a simulation, you often need the element of surprise. This is where the rand() function from the <stdlib.h> library comes in.

It generates "pseudo-random" numbers. They aren't truly random in the way a physical dice roll is, but they follow a sequence that looks random enough for most programming tasks. Think of it like a massive, pre-written book filled with billions of scrambled numbers. When you call rand(), the computer just reads the next number on the page.

Using the rand() function

The rand() function returns an integer between 0 and a very large constant called RAND_MAX (usually at least 32,767).

To use it, you simply call the function. However, because rand() gives you such a wide range of numbers, you will almost always use the modulo operator (%) to "squish" that number into a range that is useful for your program.

#include <stdio.h>
#include <stdlib.h> // Required for rand()

int main() {
    // Generate a raw random number
    int raw_number = rand();
    printf("Raw number: %d\n", raw_number);

    // Limit the range to 0-9 using modulo
    // (Any number divided by 10 leaves a remainder between 0 and 9)
    int digit = rand() % 10;
    printf("Random digit: %d\n", digit);

    // Limit the range to a dice roll (1-6)
    // We get 0-5 from the modulo, then add 1
    int dice_roll = (rand() % 6) + 1;
    printf("You rolled a: %d\n", dice_roll);

    return 0;
}

The "Groundhog Day" effect

If you run the code above multiple times, you might notice something strange: you get the exact same "random" numbers every time you start the program. This is because the "book" of numbers always starts at page one every time your program launches.

While this seems like a flaw, it is actually helpful for debugging because your program remains predictable while you are trying to fix bugs. In a later lesson, we will learn how to "seed" the generator to start on a different page every time, but for now, focus on how rand() provides the values you need to create variety in your code.

Key takeaway

Use rand() from <stdlib.h> to get a large integer, and use the % (modulo) operator to scale that number down to the specific range your program needs.