C Program to Generate a Random Number

How-to basics · Updated November 23, 2026

The simplest way to generate a random number in C is to use the rand() function from the standard library, which returns a pseudo-random integer between 0 and RAND_MAX (typically 32767). To get a number within a specific range, use the modulo operator, for example rand() % 100 for 0–99, and call srand(time(0)) once before to seed the generator so you get different sequences on each run.

How rand() Works Under the Hood

rand() is a pseudo-random number generator (PRNG) – it produces a deterministic sequence of numbers based on an internal state. The sequence looks random but is completely reproducible if you start with the same seed. The C standard only specifies that rand() returns a value between 0 and RAND_MAX; the actual algorithm is implementation-defined. Most compilers use a linear congruential generator (LCG) of the form:

state = (state * a + c) % m

where a, c, and m are constants chosen by the library. For example, glibc (used on Linux) historically used a different, more sophisticated algorithm, but the principle is the same. Because it’s deterministic, rand() is not suitable for cryptography or security-sensitive applications.

Seeding with srand()

If you don’t call srand(), the generator starts with a default seed (often 1), so every run of your program produces the same sequence. To get different numbers each run, seed it with a varying value, typically the current time:

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

int main() {
    srand(time(0));  // seed with current time
    int r = rand();
    printf("%d\n", r);
    return 0;
}

Call srand() only once at the start of your program. Calling it multiple times in a loop can produce repetitive numbers if the time doesn’t change between calls (e.g., within the same second).

Generating Numbers in a Specific Range

To get a random integer between min and max (inclusive), the common approach is:

int r = min + rand() % (max - min + 1);

For example, to simulate a dice roll (1–6):

int dice = 1 + rand() % 6;

Be aware that using modulo introduces a slight bias if the range does not evenly divide RAND_MAX+1. For most applications this bias is negligible, but if you need uniform distribution, use a rejection sampling method or a better library (see below).

Common Pitfalls and Misconceptions

  • Forgetting to seed – without srand(), you get the same sequence every run, which is often not what you want.
  • Seeding inside a loop – calling srand(time(0)) repeatedly can give the same seed if the loop runs quickly, producing identical numbers.
  • Assuming true randomness – rand() is pseudo-random; it’s predictable if you know the seed and algorithm. For security, use rand() never.
  • Modulo bias – as mentioned, rand() % n is not perfectly uniform for all n. For serious statistical work, use a better method.
  • RAND_MAX is small – on many systems it’s 32767, so if you need larger numbers, combine multiple calls or use a 64-bit generator.

Better Alternatives: rand_r, random(), and C11

For multithreaded programs, rand() is not thread-safe because it uses a shared global state. POSIX provides rand_r() which takes a pointer to an unsigned int seed:

unsigned int seed = time(0);
int r = rand_r(&seed);

On Linux and BSD, random() and srandom() are available; they produce better quality numbers with a larger state. In C11, the optional timespec_get can be used for seeding, but there is no standard random function beyond rand(). For high-quality random numbers, consider using the drand48() family (POSIX) or a third-party library like PCG or Mersenne Twister.

Generating Floating-Point Random Numbers

To get a random double between 0.0 and 1.0, divide by RAND_MAX:

double r = (double)rand() / RAND_MAX;

To get a double in a range [min, max):

double r = min + (double)rand() / RAND_MAX * (max - min);

Note that this gives discrete values because rand() returns integers; the resolution is limited to RAND_MAX+1 distinct values. For more precision, combine multiple calls or use a generator that returns 64-bit values.

Security and Cryptographic Randomness

Never use rand() for passwords, tokens, or any security-sensitive data. Its output is predictable. On Unix-like systems, read from /dev/urandom or use getrandom() (Linux) to get cryptographically secure random bytes. On Windows, use BCryptGenRandom or rand_s. In C, there’s no standard secure random function, so you must rely on platform-specific APIs.

Performance and Quality Considerations

rand() is fast and fine for simple games, simulations, or any non-critical use. However, its statistical quality is mediocre – it may fail tests like spectral randomness. If you need high-quality pseudo-random numbers for Monte Carlo simulations, use a well-tested generator like the Mersenne Twister (e.g., mt19937 in C++ or a C implementation) or PCG. For parallel programs, use separate generators per thread with different seeds.

Frequently Asked Questions

Why do I get the same random number every time I run my program?
Because you didn’t seed the generator with srand(). Without a seed, rand() starts with the same default seed, producing the same sequence. Add srand(time(0)) at the beginning of main().

How do I generate a random number between 1 and 100?
Use 1 + rand() % 100. This gives numbers from 1 to 100 inclusive. Remember to seed first.

Is rand() % n truly uniform?
No, it has a slight bias if n does not divide RAND_MAX+1 evenly. For most casual use it’s fine, but for precise work, use a rejection method or a library that guarantees uniformity.

Can I use rand() for encryption?
No. rand() is predictable and not cryptographically secure. Use a dedicated secure random source like /dev/urandom or a cryptographic library.

How do I generate a random double between 0 and 1?
Cast rand() to double and divide by RAND_MAX: (double)rand() / RAND_MAX. This gives a value in [0,1].

What is RAND_MAX?
It’s a constant defined in <stdlib.h> that represents the maximum value that rand() can return. On many systems it’s 32767, but it can be larger.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.