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.

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).

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.