-2

I am generating random numbers , and someone told me to use srand. I searched about srand and found it is used on top of rand(). But I do not understand why not use just rand() since I get random numbers in my below code:

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

int main(){

    int i=0;

    for(i=0;i<5;i++){
        printf("random number is %d\n",rand());
    }
}

And I get a set of 5 random numbers. So rand() does gives random numbers. Why do we need srand on top of that then?

Shaggy
  • 1,444
  • 1
  • 23
  • 34

1 Answers1

2

If you simply use rand() and run your code multiple times you will notice that you tend to get the same sequence of random numbers every time.

srand is used to seed the random number generator. This allows you to generate different sequences. I'd suggest that you read the manual page for srand.

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
  • You use `srand` to generate `semi-random` numbers with a `seed` to produce a **reproducible** random set to allow debugging, etc. – David C. Rankin May 06 '15 at 02:38