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 0 〜 RAND_MAX (often 2147483647). Without seeding, it produces the same sequence each run. srand(seed) sets the seed and selects a pseudorandom sequence. Call it once at the start of the program . #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(NULL)); // Seed with the current time (which changes between runs) for (int i = 0; i < 5; i++) { printf("%d\n", rand()); } return 0; }
rand() returns a large integer, so use the remainder operator % to restrict the range. // Random value from 0 through 9 int r = rand() % 10; // Random value from 1 through 6 (a die) int dice = rand() % 6 + 1; // Random value from min through max int val = rand() % (max - min + 1) + min;
| Goal | Code |
|---|---|
| 0 〜 N-1 | rand() % N |
| 1 〜 N | rand() % N + 1 |
| min 〜 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("Computer: %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: inspect the resulting histogram. As the trial count grows, the frequencies tend to become more even. rand(), srand(), and time().srand((unsigned)time(NULL)) produces the same sequence each run when srand is omitted Check 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.