C - Seed the random numbers

Introduction

The rand() function generates the same random numbers for each call.

To make the output less predictable, you need to seed the random-number generator.

That's done by using the srand() function.

The srand() function requires the stdlib.h header.

The function requires an unsigned int value, seed.

The scanf() function reads in the unsigned value by using the %u placeholder. Then the srand() function uses the seed value.

Demo

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

int main() /*w  w  w.j a va2 s.  com*/
{ 
    unsigned seed; 
    int r,a,b; 

    printf("Input a random number seed: "); 
    scanf("%u",&seed); 
    srand(seed); 
    for(a=0;a<20;a++) 
    { 
       for(b=0;b<5;b++) 
       { 
           r=rand(); 
           printf("%d\t",r); 
       } 
       putchar('\n'); 
   } 
   return(0); 
}

Result

Related Topic