Table of Contents

srand

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

Description

srand is used to initialize the random number generator.
The use of date / time to initialize the generator
means that the generated sequence of numbers “random” is.

  <time.h> is for this example nessesary

srand C Sourcecode Example

/*
 * srand exmple code
 * http://code-reference.com/c/stdlib.h/srand 
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h> /* for time to initialize srand */
 
int main ( void )
{
 
  int i;
  /* initialize random generator */
  srand ( (unsigned int) time(NULL) ); /* comment it out to see what happend */
 
  /* random number */
  for(i=0; i<=5; i++){
      printf("example %i, for srand = %d\n",i, rand());  
  }
  return 0;
}

output of srand example

  user@host:~/code-reference.com#  ./srand 
  example 0, for srand = 796883283
  example 1, for srand = 1140159597
  example 2, for srand = 137384045
  example 3, for srand = 1204700693
  example 4, for srand = 763425562
  example 5, for srand = 472690191