Random numbers are important in many real life scenarios such as computer games and statistical solutions and some computer algorithms. Nature is also full of randomness so to simulate natural objects such as clouds, mountains and tree we need random numbers.

C Standard Library provides two different methods to generate random numbers. They are:

## rand() and srand()

The rand() function alone generates the same sequence of numbers in every program run. This function can generate a random number between 0 and RAND_MAX. Here RAND_MAX macro value is at least 32767 which is the minimum number in any standard library implementation i.e. rand() function should be able to generate any random number between 0 and 32767.

Here is a simple C program to generate 10 random numbers.

1 2 3 4 5 6 7 8 9 |
#include <stdio.h> #include <stdlib.h> int main(void) { for(int counter = 0; counter < 10 ; counter++) printf(" %d ", rand()); return 0; } |

The drawback of the above program is that it prints the same random numbers every time it runs. In order to overcome the issue, another method is used to initialized the random number generator i.e. srand(). This function uses the argument (unsigned int) passed as seed. Every time a different seed is passed to this function, call to rand() function will generate different random number.

In order to provide a different seed, time() function can be used to provide a different seed every time program runs i.e. time(0).

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { time_t t; srand((unsigned) time(&t)); for(int counter = 0; counter < 10; counter ++){ printf(" %d ", rand()); } return 0; } |

## Random Number Generator

Now with the help of these two functions we can easily create a random number generator program that can generate random numbers between a range. We will use modulus operator to generate the numbers between a range.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int lower_range=0, upper_range=100, total_numbers=3; srand(time(0)); for (int i = 0; i < total_numbers; i++) { int mod = (upper_range - lower_range + 1) + lower_range; int num = (rand() % mod); printf("%d ", num); } return 0; } |