rand() in C - Source Code Example

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

rand() Function Overview

The rand() function, part of the C standard library in <stdlib.h>, helps generate random numbers. Every time you call it, a pseudo-random integer is returned. Using srand(), you can seed the random number generator to produce varied sequences of numbers in different runs of your program. Otherwise, without seeding, rand() will yield the same number sequence each program run.

Source Code Example

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

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

    // Seed the random number generator with current time
    srand(time(0));

    // Get a random number post seeding
    printf("Random number after seeding: %d\n", rand());

    // Get a random number between 0 and 99
    printf("Random number between 0 to 99: %d\n", rand() % 100);

    // Get a random number between 1 and 100
    printf("Random number between 1 to 100: %d\n", (rand() % 100) + 1);

    return 0;
}

Output

(Note: Outputs vary every program run due to randomness.)
Random number without seeding: 1804289383 (This might repeat on every run without seeding.)
Random number after seeding: 1525205839 (This changes every program run.)
Random number between 0 to 99: 37 (This changes every program run.)
Random number between 1 to 100: 74 (This changes every program run.)

Explanation

1. We get a random number without seeding. This might be consistent in every program run.

2. Then, using srand(), we seed the random generator with the current time. This ensures different numbers on each run.

3. To get a random number within a range, the modulo operator is used. Like rand() % 100 provides numbers from 0 to 99.

4. Adding 1 to rand() % 100's result changes the range from 1 to 100.

Remember, rand() is not truly random, so it's not fit for cryptographic applications.


Comments