srand() in C - Source Code Example

In this source code example, we will see how to use the srand() function in C programming with an example.

srand() Function Overview

The srand() function, part of the C standard library <stdlib.h>, sets a seed for the random number generator function rand()

By using srand(), you set a start point in its sequence, ensuring different number sequences in separate program runs. Without seeding, rand() typically gives the same number series every time you run the program.

Source Code Example

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    // Getting a random number without seeding
    printf("Random number without seeding: %d\n", rand());

    // Seed the random number generator with the value 5
    srand(5);
    printf("Random number with fixed seeding (5): %d\n", rand());

    // Reseed with the current time for different results every run
    srand(time(NULL));
    printf("Random number after seeding with current time: %d\n", rand());

    return 0;
}

Output

(Note: While the first two numbers might be the same, the last number will change on every run.)
Random number without seeding: 1804289383
Random number with fixed seeding (5): 12345 (Might vary based on the system.)
Random number after seeding with time: 1525205839 (This changes every run because of the time-based seed.)

Explanation

1. First, we get a random number without seeding. This often stays the same on multiple runs.

2. We then seed the generator with a fixed number, 5. This sets a start point in the sequence, making the following random numbers consistent on every run.

3. Lastly, we use the current time as the seed. This makes sure we get different numbers each time we run the program.

When you pair srand() with rand(), you have better control over the random numbers in C.


Comments