• Register
Log In

When we write the program for generating random numbers, we use different functions like rand(), srand() and srand(time(null)). We know that rand() helps us in generating random numbers using an algorithm and srand(time(null)) helps us to generate different random numbers each time we run the program. But what actually srand(time(null)) does in the program? What is its functionality? We are going to discuss this function in this article. But before understanding functionality of srand(time(null)) we should know about the functionality of srand().



This function is used to set the starting value (known as seed) for generating a sequence of pseudo-random integer values. The seed of the random number generator algorithm used by the function rand() is set by the function srand(x). A seed value of 1 is the default setting yielding the same sequence of values as if srand(x) were not used. Any other value for the seed produces a different sequence. 



 By using this function we make use of the computer’s internal clock to control the choice of the seed. The seed is forever changing since the time is continuously changing. If the seed number remains the same, then the sequence of the numbers will be repeated for each program run.

For example

/*generate 10 random numbers between 10 and 55 inclusive, without repetition of the sequence between program runs*/

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

int main(void)
     // to prevent sequence repetition between runs     

     for(int i = 1; i <=10; i++)     // looping to print 10 numbers
           cout<< 10 + rand( ) % 46;   // formula for numbers 

     return 0;

If we run this program then it will generate random numbers for each program run. But if remove the function srand(time(null)) then it will repeat the sequence of the random numbers generated each time we run the program.

posted Jun 20 in c++ 100 points