What is the purpose of srand(time(NULL)) in C?

QuestionsQuestions8 SkillsProImplement Loops In CSep, 06 2025
02.1k

The function call srand(time(NULL)) in C is used to seed the random number generator. Here's a breakdown of its purpose:

  1. Seeding the Random Number Generator: The srand() function initializes the random number generator used by the rand() function. By providing a seed value, you ensure that the sequence of random numbers generated by rand() is different each time the program is run.

  2. Using time(NULL): The argument time(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.

0 Comments

no data
Be the first to share your comment!