C Program to Generate Random Numbers

1. Introduction

Generating random numbers in programs can be useful for various reasons such as simulations, games, and testing. In C, we can produce random numbers with the help of the rand() function available in the stdlib.h library. However, by default, this function generates the same sequence of numbers every time the program runs. To overcome this and produce a different sequence on each execution, we use the srand() function with the current time as the seed.

2. Program Overview

1. Include necessary header files.

2. Use srand() to initialize the random number generator with the current time.

3. Use the rand() function to generate random numbers.

4. Display the generated numbers.

3. Code Program

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

int main() {
    int i, n;

    // Initialize random number generator
    srand(time(0));

    printf("How many random numbers do you want to generate?: ");
    scanf("%d", &n);

    printf("Random Numbers: \n");
    for(i = 0; i < n; i++) {
        printf("%d\n", rand());
    }

    return 0;
}

Output:

How many random numbers do you want to generate?: 5
Random Numbers:
12345
67890
23456
78901
23457
(Note: Actual numbers will vary on each execution.)

4. Step By Step Explanation

1. The program begins by including the necessary header files: stdio.h for input/output functions, stdlib.h for the rand() and srand() functions, and time.h for the time() function.

2. The random number generator is initialized using the current time (time(0)) as the seed. This ensures that each time the program runs, we get a different sequence of random numbers.

3. The user is prompted to enter the number of random numbers they wish to generate.

4. A loop runs as many times as the user specifies, and inside this loop, the rand() function is called to produce a random number, which is then printed.

Comments