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()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q