C programming srand stdlib.h


In C programming the <stdlib.h> srand function provide a way to use a value as a seed for a new sequence of pseudo-random number.The declaration of the function is shown below.

void srand(unsigned int seed);

Parameters:
seed – A value to be used as seed for new sequence of pseudo-random numbers.Another way to interpret seed is it help generate different sequence for different seed values.In this way the predictability of the sequence is lessen.

Return type
void

Some points to note:

i) If srand is called with the same seed the pseudo-random sequence shall be repeated.

ii) If rand function is called before srand is called providing the seed as 1 will repeat the sequence.

iii) The implementation shall behave as if no library function calls the srand function.

LinK: C <stdlib.h> rand

Code example

srand(26);

for (int i = 0; i < 5; i++) { printf("%i\n", rand( ) );
}

printf( “\n\n” );
srand(26);

for (int i = 0; i < 5; i++) { printf("%i\n", rand() );
}

Output in VS,

123
25034
26954
5491
14890

123
25034
26954
5491
14890

You can see that the output is repeated when the seed is set to the same value 26.





Use of srand function

Why is calling/using ‘srand’ necessary? we know using ‘rand’ function can generate pseudo-random sequence,but if you run the program every time,the sequence obtain is the same.This simply means the ‘rand’ function is not so random because running the same program generate the same sequence.Consider the code below.

for(int i=0; i<5 ;i++)
{
printf(“%i\n” ,rand( ) );
}

Output in Code::Block,

41
18467
6334
26500
19169

Close the program,run the code again,not-surprisingly you will see the same sequence generated.Now this can be inconvenient for some programs whose workings depend on the non-uniformity of the random numbers generated.So,the predictability of the random number sequence is not exactly what you want.Now,’srand’ come into play.Setting the seed to different value every time you run the program will ensure that the sequence generated is also different every time you run the program.

If you set the seed value to just one same value the sequence generated is also same,the most common way to ensure the randomness of the sequence is to use ‘time’ function to generate the seed value .The ‘time'(found in <time.h> ) function will generate different values every time you run the program,this in-turn ensure that the sequence generated is also random.

A code example using ‘time’ to get different seed value every time you run the program is shown below.Include the header <time.h>.

Code example

srand( time(NULL) );

for(auto i=0; i<5 ; i++)
{
printf(“%i\n”, rand( ) );
}

First output in VS,

30405
29722
12825
24019
21109

Second output,
30503
24495
24462
25022
2866

Now you get a new pseudo-random sequence every time you run the program.