srand c – srand C Library Function

Srand c: The function void srand(unsigned int seed); initializes the pseudo random number generator used by the function rand. If we provide different value of seed to a srand function then corresponding rand functions calls will generate different sequence of pseudo random numbers.

Two different initializations of srand with the same seed value will generate the same sequence of pseudo random numbers in subsequent calls to rand.

Function prototype of srand

void srand(unsigned int seed);
  • seed : This is an integer value, which is the seed for pseudo random number generation algorithm used by rand function.

Return value of srand

NONE

C program using srand function

Srand in c: The following program shows the use of srand and rand function to generate a sequence of pseudo random numbers.

srand C Library Function

#include <stdio.h>
#include <stdlib.h>
 
int main(){
    unsigned int seed;
    int n, counter;
 
    printf("Enter a unsigned number(seed)\n");
    scanf("%u", &seed);
     
    /* Initialize random number generator using srand */
    srand(seed);
     
    printf("Enter number of random numbers\n");
    scanf("%d", &n);
    for(counter=0; counter < n; counter++){
        printf("%d ", rand());
    }
     
    return 0;
}

Output

Enter a unsigned number(seed)
234
Enter number of random numbers
7
802 32478 7150 29924 30401 13148 15783