Easy Tutorial
❮ C Exercise Example21 C Macro Va_End ❯

C Library Function - srand()

C Standard Library - <stdlib.h>

Description

The C library function void srand(unsigned int seed) seeds the random number generator used by the function rand.

Declaration

Here is the declaration for the srand() function.

void srand(unsigned int seed)

Parameters

Return Value

This function does not return any value.

Example

The following example demonstrates the use of the srand() function.

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

int main()
{
   int i, n;
   time_t t;

   n = 5;

   /* Initialize random number generator */
   srand((unsigned) time(&t));

   /* Print 5 random numbers from 0 to 50 */
   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 50);
   }

  return(0);
}

Let's compile and run the above program, which will produce the following result:

38
45
29
29
47

C Standard Library - <stdlib.h>

❮ C Exercise Example21 C Macro Va_End ❯