Exploring the Usage of the rand() Function for Random Number Generation in C

24 Feb 2023 Balmiki Mandal 0 C Programming

Understanding the rand() Function in C: Generating Random Numbers

The rand() function is a built-in function in the C programming language that is used to generate random numbers. It is defined in the stdlib.h header file.

The rand() function generates a sequence of pseudo-random integers between 0 and RAND_MAX, which is a constant defined in stdlib.h. The actual sequence of numbers generated by rand() depends on the seed value that is set using the srand() function.

The syntax of the rand() function is as follows:

int rand(void);

The return type of the rand() function is int, which is a random integer between 0 and RAND_MAX.

C program that demonstrates how to use the rand() function

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

int main() {
    int i, num;
    
    // Set the seed value using the time function
    srand(time(NULL));
    
    // Generate 5 random numbers
    for (i = 0; i < 5; i++) {
        num = rand();
        printf("%d\n", num);
    }
    
    return 0;
}

In this example, the srand() function is used to set the seed value using the current time, which ensures that the sequence of random numbers generated rand() is different every time the program is run. The rand() function is called five times in a loop to generate five random numbers, which are then printed to the console using the printf() function.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.