C library - srand() function



The C stdlib library srand() function is used to initialize or sets the seed for the 'rand()' function, allowing us to generate different sequence of the random number. By default the seed value is 1 for the rand() function.

Syntax

Following is the C library syntax of the srand() function −

void srand(unsigned int seed)

Parameters

This function accepts a single parameter −

  • seed − It is an unsigned integer that represents the seed value.

Return Value

This function does not returns any value.

Example 1

Let's create a basic c program to demonstrate the use of srand() function.

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

int main() {
   // Set seed based on current time
   srand(time(NULL)); 
   int i;
   for (i = 0; i < 10; i++) {
      int value = rand();
      printf("%d ", value);
   }
   return 0;
}

Output

Following is the output, which always display random number −

22673 30012 9907 5463 13311 32059 17185 6421 15090 23066

Example 2

The below is the another example, we will generate random numbers within a specific range. Using srand() and srandrand() functions.

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main() {
   // Lower bound
   int lb = 20; 
   // Upper bound
   int ub = 100;
   
   // Initialize random seed based on current time
   srand(time(NULL)); 
   
   int i;
   for (i = 0; i < 5; i++) {
      // Generate a random number between lb and ub (inclusive)
      printf("%d ", (rand() % (ub - lb + 1)) + lb );
   }
   return 0;
}

Output

Following is the output, which always display random number −

44 77 70 86 75
Advertisements