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.
The rand() function returns a pseudo-random integer between 0 and RAND_MAX (a constant defined in stdlib.h, usually 32767).
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.
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 |
This example demonstrates how to generate a random number between 1 and 6, simulating a standard six-sided die.
rand() is not cryptographically secure. For security-related tasks (like generating passwords), specialized libraries are needed.srand(time(NULL)) once at the beginning of your main() function. Calling it inside a loop will likely result in the same "random" number.rand() will not exceed the RAND_MAX value of your specific compiler.| Header | <stdlib.h> (and <time.h> for seeding) |
| Mechanism | Linear Congruential Generator (LCG) |
| Repeatability | Fixed seed results in fixed sequences (useful for debugging). |
srand(42);) instead of time(NULL). This ensures the "random" sequence is the same every time you run the test!