How to use rand() and srand() in C. Ranges, seeds, and applications illustrated.
srand((unsigned)time(NULL));rand()rand() % N for 0 to N-1RAND_MAX and modulo biasrand() function from stdlib.h. They're called "pseudo" because a mathematical formula produces them internally, so they aren't truly random — but for everyday use, they're good enough.
#include <stdlib.h> // rand(), srand() #include <time.h> // time() - for the seed
rand() returns an integer in the range 0 to RAND_MAX (typically 2147483647). But if you call it as-is, you'll get the same sequence every time.
srand(seed) sets the random number "seed," and each seed produces a different sequence. Call it once, at the start of your program.
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(NULL)); // seed from current time (different every run) for (int i = 0; i < 5; i++) { printf("%d\n", rand()); } return 0; }
rand() returns very large numbers, so use the modulo operator % to narrow the range down.
// 0 to 9 int r = rand() % 10; // 1 to 6 (a die) int dice = rand() % 6 + 1; // min to max int val = rand() % (max - min + 1) + min;
| Goal | Code |
|---|---|
| 0 to N-1 | rand() % N |
| 1 to N | rand() % N + 1 |
| min to max | rand() % (max - min + 1) + min |
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { char *hands[] = {"Rock", "Scissors", "Paper"}; srand(time(NULL)); int cpu = rand() % 3; // 0:Rock 1:Scissors 2:Paper printf("CPU: %s\n", hands[cpu]); return 0; }
// Fisher-Yates shuffle for (int i = n - 1; i > 0; i--) { int j = rand() % (i + 1); // swap a[i] and a[j] int tmp = a[i]; a[i] = a[j]; a[j] = tmp; }
rand() % N really uniformly distributed? A histogram tells you. The more trials you run, the more even the distribution becomes.
rand(), srand(), and time().#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(NULL)); // Roll a die 10 times for (int i = 0; i < 10; i++) { int dice = rand() % 6 + 1; printf("Roll %d: %d\n", i + 1, dice); } return 0; }
srand(time(NULL)) and see identical runsCheck your understanding!
rand() returns an integer between 0 and RAND_MAX (usually at least 32767). Use the % operator to narrow it to a specific range.
srand() sets the seed for the random number generator. Since the same seed always produces the same sequence, time(NULL) is a common choice.
rand() % 6 returns 0 through 5, so adding 1 gives you 1 through 6. rand() % 7 would return 0 through 6.