Generate random number in C/C++ programming language.

Spread the love

random number generator program in c and cpp

Generating Random number in C++:

We will use the  rand()  function from the cstdlib  library.  rand() will generate one random number for each call. we will get one random number between the 0 to RAND_MAX  for each call. please look at the following code.

Program: Random number generator in C/C++:

Output:

We can also limit the maximum number using %  Modulus operator with the rand function.

For example following rand function will generate one random value between the 0 to 100 for each call.

Ex2: following rand() function generates a number between the 1 to 100.

Here is the same program but in this case, it will generate a random number between the 1 to 100.

Program to generate the random numbers between the 1 to 100 :

Output:

But if you observe the above output, you will notice our random number generator is generating same set of random numbers each time program executed.

To make our program to be a completely random number generator we need to use srand() function. srand function takes one argument seed.

Prototype of srand() function:

But if we use some static number like srand(123) , It will still generate the same set of numbers. Because we are feeding the same number every time.

So we need to use different seed value each time we run the program. So the best solution to this is using time()  function from  ctime  library. It will generate the number of seconds from Epoch.
So we can guarantee our program always receives the random seed number for srand()  function. So we will get random numbers whenever we call the rand()  function.

Random number generator program with srand and time functions:

Output:

This way we can generate the random numbers in C/C++.

 

Venkatesh Macha

Hi Guys, I am Venkatesh Macha. Founder of SillyCodes. I am a programmer, Presently working as a Software Engineer in Hyderabad. I love Linux and Open Source. Apart from that, I love to explore new technologies and things.

You may also like...

Leave a Reply