The function call srand(time(NULL)) in C is used to seed the random number generator. Here's a breakdown of its purpose:
-
Seeding the Random Number Generator: The
srand()function initializes the random number generator used by therand()function. By providing a seed value, you ensure that the sequence of random numbers generated byrand()is different each time the program is run. -
Using
time(NULL): The argumenttime(NULL)returns the current time in seconds since the Epoch (January 1, 1970). This value changes every second, making it a good choice for a seed. By using the current time, you ensure that the seed is different for each execution of the program, leading to different sequences of random numbers.
Here’s an example of how it is typically used:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // Seed the random number generator
// Generate and print 5 random numbers
for (int i = 0; i < 5; i++) {
printf("%d\n", rand());
}
return 0;
}
In this example, each time you run the program, it will produce a different set of random numbers due to the seeding with the current time.
