w3resource

C srand() function

C srand() function - Pseudo-random number generator

Syntax srand() function

void srand(unsigned int seed)

The srand() function is used to set the starting point for producing a series of pseudo-random integers. Rand() seed is set as if srand(1) were called at program start if srand() is not called.

Parameters srand() function

Name Description Required /Optional
seed Seed for pseudorandom number generation Required

Return value from srand()

  • There is no return value.

Example: srand() function

The following example, first srand() is called with a value other than 1 to initiate the random value sequence. As a result, the program calculates eleven random values for the array of integers, known as ranvals.

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

int main(void)
{
   int i, ranvals[10];
 
   srand(27);
   for (i = 0; i < 15; i++)
   {
      ranvals[i] = rand();
      printf("Iteration %d ranvals [%d] = %d\n", i+1, i, ranvals[i]);
   }
}

Output:

Iteration 1 ranvals [0] = 126
Iteration 2 ranvals [1] = 3014
Iteration 3 ranvals [2] = 12050
Iteration 4 ranvals [3] = 29554
Iteration 5 ranvals [4] = 25204
Iteration 6 ranvals [5] = 19515
Iteration 7 ranvals [6] = 26865
Iteration 8 ranvals [7] = 18785
Iteration 9 ranvals [8] = 30279
Iteration 10 ranvals [9] = 28454
Iteration 11 ranvals [10] = 1860

C Programming Code Editor:

Previous C Programming: C rand()
Next C Programming: C mblen()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/stdlib/c-srand.php