How does srand() work?

QuestionsQuestions4 SkillsProImplement Loops In CSep, 06 2025
0193

The srand() function in C is used to set the seed for the random number generator that is used by the rand() function. Here's how it works:

  1. Seeding the Generator: When you call srand(seed), you provide a seed value (an integer). This seed initializes the random number generator's internal state. The seed determines the starting point for the sequence of pseudo-random numbers that will be generated by rand().

  2. Deterministic Output: The sequence of numbers produced by rand() is deterministic, meaning that if you start with the same seed value, you will get the same sequence of random numbers every time you run the program. For example, if you call srand(1) and then call rand(), you will always get the same sequence of numbers for that seed.

  3. Using time(NULL): To get different sequences of random numbers on each run of the program, it is common to use srand(time(NULL)). This uses the current time as the seed, which changes every second, ensuring that the random numbers generated are different each time the program is executed.

  4. Example: Here’s a simple example demonstrating srand() and rand():

    #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 summary, srand() is essential for controlling the randomness of the numbers generated by rand(), allowing for varied outputs in different runs of the program.

0 Comments

no data
Be the first to share your comment!