srand() — Set Seed for rand() Function

Format

#include <stdlib.h>
void srand(unsigned int seed);

Language Level: ANSI

Threadsafe: No.

Description

The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at program start. Any other value for seed sets the generator to a different starting point.

The rand() function generates the pseudo-random numbers.

Return Value

There is no return value.

Example that uses srand()

This example first calls srand() with a value other than 1 to initiate the random value sequence. Then the program computes five random values for the array of integers that are called ranvals.

#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   int i, ranvals[5];
 
   srand(17);
   for (i = 0; i < 5; i++)
   {
      ranvals[i] = rand();
      printf("Iteration %d ranvals [%d] = %d\n", i+1, i, ranvals[i]);
   }
}
 
/******************  Output should be similar to:  ****************
 
Iteration 1 ranvals [0] = 24107
Iteration 2 ranvals [1] = 16552
Iteration 3 ranvals [2] = 12125
Iteration 4 ranvals [3] = 9427
Iteration 5 ranvals [4] = 13152
*/

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]