Random Numbers in C
Our program will demonstrate generating random numbers in C. Here’s the full source code:
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:
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.