rand() / srand()
Functions for generating pseudo-random numbers. Use them when you need unpredictable values, such as in games or numerical simulations. A given seed value always produces the same sequence of random numbers.
Syntax
// Returns a pseudo-random integer between 0 and RAND_MAX (inclusive). // RAND_MAX is implementation-defined but is at least 32767. int rand(void); // Sets the seed for the random number generator. // Passing the same seed always produces the same sequence of random numbers. void srand(unsigned int seed);
Common Patterns
| Purpose | Example | Description |
|---|---|---|
| Initialize seed | srand((unsigned)time(NULL)) | Uses the current time as the seed so each run produces a different sequence. |
| Integer from 0 to N-1 | rand() % N | Uses the modulo operator to limit the range. Note that this can introduce a slight bias. |
| Integer from MIN to MAX | MIN + rand() % (MAX - MIN + 1) | Adds an offset to shift the range. |
| Float from 0.0 to 1.0 | (double)rand() / RAND_MAX | Divides by RAND_MAX to produce a floating-point value in [0.0, 1.0]. |
Sample Code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
// Seed with the current time so each run produces a different sequence.
srand((unsigned int)time(NULL));
// Roll a six-sided die 5 times.
printf("Dice rolls: ");
for (int i = 0; i < 5; i++) {
int dice = 1 + rand() % 6;
printf("%d ", dice);
}
printf("\n");
// Generate 3 random floating-point values between 0.0 and 1.0.
printf("Floating-point randoms: ");
for (int i = 0; i < 3; i++) {
double r = (double)rand() / RAND_MAX;
printf("%.4f ", r);
}
printf("\n");
// Using the same seed always produces the same sequence (reproducibility check).
srand(42);
printf("seed=42: ");
for (int i = 0; i < 5; i++) {
printf("%d ", rand() % 100);
}
printf("\n");
return 0;
}
Notes
The quality of values returned by rand() — including distribution bias and cycle length — is implementation-defined. Do not use rand() for security-sensitive purposes such as password generation or cryptography. For those use cases, rely on a secure random source provided by the OS (such as /dev/urandom on Unix-like systems).
When using rand() % N, small values may appear slightly more often if RAND_MAX is not a multiple of N. If you need high-quality random numbers, consider alternatives from C11 Annex K or an external library.
To get the current time for seeding, see time().
If you find any errors or copyright issues, please contact us.