How to Generate a Random Number in C

Random number generation is a crucial aspect of computer programming, particularly in applications that involve simulations, games, and statistical analysis.

The C programming language provides various methods to generate random numbers, each with its own advantages and disadvantages.

In this C language tutorial, we will discuss the different methods to generate random numbers in C and provide code examples to help you understand the process better.


Standard Library Function: rand()

The most commonly used method to generate random numbers in C is the rand() function, which is part of the standard library.

The rand() function returns a pseudo-random integer between 0 and RAND_MAX, where RAND_MAX is a constant defined in the standard library.

Here is an example of how you can use the rand() function to generate a random number between 0 and 9:

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

int main() {
    srand(time(NULL));
    int random_number = rand() % 10;
    printf("Random number: %d\n", random_number);
    return 0;
}

Seeding the rand() Function: srand()

The rand() function generates the same sequence of random numbers every time the program is executed.

To overcome this, the srand() function is used to seed the random number generator with a different seed value every time the program is executed.

The seed value is usually obtained from the current time using the time() function.

Linear Congruential Generator (LCG): rand_r()

The rand() function is not suitable for use in multi-threaded applications as it uses a shared state, which can lead to unexpected results.

To overcome this, the rand_r() function can be used instead.

The rand_r() function generates a pseudo-random number using a linear congruential generator (LCG) and does not use a shared state, making it suitable for use in multi-threaded applications.

Here is an example of how you can use the rand_r() function to generate a random number between 0 and 9:

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

int main() {
    unsigned int seed = time(NULL);
    int random_number = rand_r(&seed) % 10;
    printf("Random number: %d\n", random_number);
    return 0;
}

The random number generator functions in C are suitable for most applications but may not provide high-quality random numbers for cryptographic or security-sensitive applications.

For such applications, it is recommended to use a library such as OpenSSL, which provides secure random number generation functions.


Conclusion

In conclusion, generating random numbers in C is an essential aspect of computer programming and has various applications.

The C programming language provides various methods to generate random numbers, including the rand() function, the srand() function, and the rand_r() function.