Random Numbers in C
Our program will demonstrate generating random numbers in C. Here’s the full source code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// Seed the random number generator
srand(time(NULL));
// Generate random integers between 0 and 99
printf("%d,%d\n", rand() % 100, rand() % 100);
// Generate a random float between 0.0 and 1.0
printf("%f\n", (float)rand() / (float)RAND_MAX);
// Generate random floats between 5.0 and 10.0
printf("%f,%f\n",
5.0 + ((float)rand() / (float)RAND_MAX) * 5.0,
5.0 + ((float)rand() / (float)RAND_MAX) * 5.0);
// Use a known seed for reproducible results
srand(42);
printf("%d,%d\n", rand() % 100, rand() % 100);
// Using the same seed will produce the same sequence
srand(42);
printf("%d,%d\n", rand() % 100, rand() % 100);
return 0;
}
Let’s break down the code and explain each part:
We include necessary headers:
stdio.h
for input/output,stdlib.h
for the random number functions, andtime.h
for seeding the random number generator.In the
main
function, we first seed the random number generator usingsrand(time(NULL))
. This ensures that we get different random numbers each time we run the program.We use
rand() % 100
to generate random integers between 0 and 99, and print two of them.To generate a random float between 0.0 and 1.0, we divide the result of
rand()
byRAND_MAX
.For random floats between 5.0 and 10.0, we use the formula
5.0 + (rand() / RAND_MAX) * 5.0
.To demonstrate using a known seed, we call
srand(42)
and then generate two random numbers. We do this twice to show that using the same seed produces the same sequence of random numbers.
To compile and run the program:
$ gcc random_numbers.c -o random_numbers
$ ./random_numbers
68,56
0.840125
5.937056,6.840125
94,49
94,49
Note that the actual numbers generated may be different when you run the sample, except for the last two lines which use a fixed seed.
The C standard library’s random number generator is relatively simple. For more advanced random number generation, consider using external libraries or implementing more sophisticated algorithms.