Yes, C can generate a random number in a specific range using the rand() function from <stdlib.h>, combined with the modulo operator and an offset. The general formula is int random = (rand() % (max - min + 1)) + min;, but this simple approach has known biases and limitations that you should understand before using it in real code.
How rand() Works Under the Hood
The C standard library provides rand(), which returns a pseudo-random integer between 0 and RAND_MAX (a constant defined in <stdlib.h>). On most systems, RAND_MAX is 32767, though on some modern platforms it can be larger (e.g., 2147483647 on glibc). The sequence is deterministic: given the same seed, rand() produces the exact same sequence every time. To get different sequences across runs, you call srand() with a changing seed, typically the current time:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand((unsigned)time(NULL));
int r = rand();
printf("%d\n", r);
return 0;
}
The time() function returns seconds since the epoch, so if you call srand() twice within the same second, you get the same sequence. For better seeding, consider clock_gettime() or reading from /dev/urandom on POSIX systems.
The Basic Range Formula and Its Bias
To map rand() to a range [min, max] (inclusive), you use:
int random_in_range(int min, int max) {
return (rand() % (max - min + 1)) + min;
}
For example, to get a number between 1 and 6 (like a die roll): int die = (rand() % 6) + 1;. This works because rand() % 6 gives a value from 0 to 5, then adding 1 shifts it to 1–6.
However, this method suffers from modulo bias when RAND_MAX + 1 is not evenly divisible by the range size. For instance, if RAND_MAX is 32767 and you want a number from 0 to 2 (range size 3), the numbers 0 and 1 appear 10923 times each, but 2 appears only 10922 times because 32768 % 3 = 2. Over many calls, this slight skew can matter in simulations or games. For small ranges and non-critical uses, the bias is negligible, but for cryptographic or statistical applications, you need a better method.
How to Eliminate Modulo Bias
The standard fix is to reject values that would cause bias. Here’s a common implementation:
int random_in_range_unbiased(int min, int max) {
int range = max - min + 1;
int limit = RAND_MAX - (RAND_MAX % range);
int r;
do {
r = rand();
} while (r >= limit);
return (r % range) + min;
}
This discards any rand() output that falls in the last partial bucket. For RAND_MAX = 32767 and range 3, limit becomes 32766 (since 32767 % 3 = 1, so 32767 – 1 = 32766). Values 32766 and 32767 are rejected, making each remainder 0, 1, 2 equally likely. The loop runs at most a couple of times in practice.
Seeding: srand() and Common Pitfalls
Always call srand() once at the start of your program, not inside a loop or before every rand() call. A common mistake is seeding with srand(time(NULL)) inside a loop that runs faster than one second, causing repeated identical numbers. Another pitfall is forgetting to include <time.h> or using srand() without a seed, which defaults to seed 1 and gives the same sequence every run.
For better randomness, use a higher-resolution seed:
#include <time.h>
#include <stdint.h>
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
srand((unsigned)(ts.tv_nsec ^ ts.tv_sec));
On Windows, you can use GetTickCount64() or rand_s() for a cryptographically secure random number, but that’s platform-specific.
Alternatives: rand_r, random(), and C11’s rand_s
For multi-threaded programs, rand() is not thread-safe because it uses a global state. POSIX provides rand_r(), which takes a pointer to an unsigned int state variable:
unsigned int seed = 12345;
int r = rand_r(&seed);
On Linux/BSD, random() and srandom() produce better quality numbers with a larger period (up to 2^31-1). For cryptographic security, use getrandom() on Linux, arc4random() on BSD/macOS, or rand_s() on Windows (which uses the operating system’s CSPRNG). C11’s rand_s() is optional and not widely implemented; instead, use the C11 nrand48() family if available.
For modern C (C11 and later), you can also use timespec_get() for seeding, but there’s no standard high-quality RNG in the C standard library—only rand().
Common Mistakes and How to Avoid Them
- Off-by-one errors: For a range from 0 to N, use
rand() % (N+1). For a range from 1 to N, use(rand() % N) + 1. - Using
%with negative numbers: Ifminis negative, the formula still works becauserand()is non-negative, but be careful with integer overflow whenmax - min + 1exceedsINT_MAX. - Not casting to larger types: When range is large,
rand() * (max - min + 1)can overflow int; uselong longordouble. - Forgetting to include
<stdlib.h>: This causes implicit declaration errors. - Using
rand() % 1: This always gives 0, so if you want a single value, just returnmin.
Practical Examples: Dice, Arrays, and Shuffling
Here’s a complete program that rolls a die 10 times:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
for (int i = 0; i < 10; i++) {
int die = (rand() % 6) + 1;
printf("%d ", die);
}
printf("\n");
return 0;
}
To pick a random element from an array, generate an index: int idx = rand() % size;. For shuffling, use the Fisher-Yates algorithm, which requires random indices in a decreasing range—use the unbiased function above for better quality.
Performance and Thread Safety
rand() is fast—typically a few nanoseconds per call—but it holds a global lock in some implementations, making it slow under heavy multi-threaded use. For high-performance applications, consider using a thread-local PRNG like rand_r() or implement a simple xorshift generator yourself. For example:
static unsigned long long rng_state = 12345;
unsigned long long xorshift64() {
rng_state ^= rng_state << 13;
rng_state ^= rng_state >> 7;
rng_state ^= rng_state << 17;
return rng_state;
}
This is not cryptographically secure but is much faster and has good distribution for simulations.
Frequently Asked Questions
Why does rand() return the same sequence every time?
Because rand() is a pseudo-random generator with a fixed algorithm. Without calling srand(), the seed defaults to 1, so the sequence is always identical. Calling srand(time(NULL)) changes the seed based on the current time, giving a different sequence each run (unless you run twice in the same second).
Is rand() % N truly random?
No, it’s pseudo-random and has modulo bias when N does not evenly divide RAND_MAX + 1. For most non-critical uses, the bias is tiny, but for simulations or games where fairness matters, use the rejection method described above.
How do I generate a random floating-point number between 0 and 1?
Use double r = (double)rand() / (RAND_MAX + 1.0); to get a value in [0, 1). To get a number in [0, 1], use (double)rand() / RAND_MAX. To get a float in a custom range, multiply and add: min + r * (max - min).
Can I use rand() in multi-threaded programs?
Yes, but it’s not thread-safe because the internal state is shared. Use rand_r() with a per-thread seed variable, or use a thread-local PRNG. Alternatively, use platform-specific functions like arc4random() which are thread-safe.
What is the maximum range I can generate?
With rand(), the maximum range is limited by RAND_MAX (usually 32767). To generate numbers larger than that, combine multiple calls or use a different generator like random() or a 64-bit PRNG.
Is there a standard C function for random numbers in a range?
No, the C standard only provides rand() and srand(). Range generation is left to the programmer. Some libraries like POSIX offer random(), but it’s not standard C.
Related
- Tab Switching Shortcuts: Ctrl+Tab, Ctrl+Page Down & More
- Python Random Numbers: How to Generate Them
- Data Entry Computer Course: What It Covers & Is It Worth It?
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Insert an Image as an Object in Microsoft ExcelTo insert an image as a movable object in Excel for Microsoft 365 on Windows, select the worksheet,…
- Java String Built-In Methods: Uses, Examples, and TipsJava’s built-in string operations are methods of the String class, rather than standalone functions. Common examples include length()…
- Simple Checklist Template Excel: Build a Useful OneA simple checklist template in Excel needs a task column, a status column, and optional fields for an…
- Creating a Booklet in Word: Setup, Pages, and PrintingTo create a booklet in Microsoft Word for Microsoft 365 on Windows, open Layout > Margins > Custom…
- Excel: Hide Duplicates Based on One Column in a ListTo hide entire rows when a value repeats in one column, add a helper column, mark the first…
- Excel Table to Markdown: Ways to Convert and FormatExcel has no built-in command that exports a range or table directly as Markdown. To convert one, copy…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.