srand

The srand function is used to initialize the pseudo random generator "rand", provided by the C library. The srand function can be used in two ways. Using a fixed argument, the srand will cause the rand function to output always the same sequence of pseudo-random numbers. Another way is to use a different number everytime (using time data, network data, etc.) to generate a sequence that is different. The first use of rand should be preceded by a call to srand.

The rand function requires only one argument, the integer value that is stored as the seed for the sequence of random numbers.

The following code shows an example of srand in use:

#include <stdlib.h>
#include        <stdio.h>

int main()
{
        int i;
        int num_elements = 10;
        srand(0);
        rand();
        for (i=0; i<num_elements; i++) {
                printf("the value is %d\n", rand());
        }
        return 0;
}

The output of this program is:

the value is 1481765933
the value is 1085377743
the value is 1270216262
the value is 1191391529
the value is 812669700
the value is 553475508
the value is 445349752
the value is 1344887256
the value is 730417256
the value is 1812158119
Article created on 2008-08-19 22:12:40

Post a comment