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

Scaling `rand` results to a specific range

Scaling rand results to a specific range

What you'll learn: How to use the modulo operator to transform large random integers into a useful range for your programs.

The Problem with Raw Randomness

In C, the rand() function is like a giant lottery machine. Every time you call it, it spits out an integer between 0 and RAND_MAX (which is at least 32,767, but often much higher).

While a giant number like 21,474,836 is great for some things, it’s not helpful if you are trying to simulate a six-sided die roll or pick a random index in an array of ten items. To make these numbers useful, we need to "squash" them down into a range that fits our needs.

The Modulo Shortcut

The most common way to scale a random number is by using the modulo operator (%). Think of modulo as the "remainder" operator. If you divide any number by 6, the remainder can only be 0, 1, 2, 3, 4, or 5. It is impossible to get a remainder of 6 or higher.

By using rand() % N, you force the result to stay within the range of 0 to N-1.

Shifting the Range

If you want a range that doesn't start at zero—like a die roll (1 to 6) instead of (0 to 5)—you simply add an offset. The formula looks like this:

result = (rand() % range) + min;

Here is how you would implement a simple die roll in C:

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

int main() {
    // Seed the random number generator
    srand(time(NULL));

    // 1. Define the range (6 possible outcomes)
    // 2. Define the starting point (1)
    int die_roll = (rand() % 6) + 1;

    printf("You rolled a: %d\n", die_roll);

    // Another example: A random percentage (0 to 100)
    int chance = rand() % 101;
    printf("Success chance: %d%%\n", chance);

    return 0;
}

Why This Works

Think of it like a clock. If you start at 12 and move forward 50 hours, you don't end up at "hour 50." You wrap around the circle multiple times until you land on 2. The modulo operator works exactly the same way; it wraps the massive number returned by rand() around your small target range until it fits.

Key takeaway

To get a random number within a specific range, use (rand() % range) + min_value.