# Random number generator function rand() vs srand(time(NULL));

 Abishek Dhanpal · November 8, 2015 The random number generator function rand(), when used in a program always gives a specific random number when you run the code again and again. For instance when you run it for the first time it generates a number 41 then when you run it for any number of times it generates the same number. Surprisingly i found a solution for this problem by inserting a special function  srand(time(NULL)); . However if someone knows how this works please illustrate. And Thanks Bucky for the wonderful youtube tutorials``#include #include #include #include #include int main(){    int i=0;    int dice1,dice2,dice3,dice4,dice5,dice6;    char player1[20];    char player2[20];    int total1=0;    int total2=0;    srand(time(NULL));    printf("welcome to dice_game\n");    printf("enter player1 name:");    scanf("%s",player1);    printf("enter player2 name:");    scanf("%s",player2);    for(i=0;i<1;i++){        dice1=(rand()%6)+1;        printf("%d\n",dice1);    }     for(i=0;i<1;i++){        dice2=(rand()%6)+1;        printf("%d\n",dice2);    }     for(i=0;i<1;i++){        dice3=(rand()%6)+1;        printf("%d\n",dice3);    }     total1=dice1+dice2+dice3;     printf("total1 is: %d\n",total1);srand(time(NULL));  for(i=0;i<1;i++){        dice4=(rand()%6)+1;        printf("%d\n",dice4);    }     for(i=0;i<1;i++){        dice5=(rand()%6)+1;        printf("%d\n",dice5);    }     for(i=0;i<1;i++){        dice6=(rand()%6)+1;        printf("%d\n",dice6);    }     total2=dice4+dice5+dice6;     printf("total2 is: %d\n",total2);     if(total1>total2){        printf("%s has won",player1);     }       if(total1

## Replies

 Jon Z. · November 8, 2015 srand seeds the random number generator http://www.cplusplus.com/reference/cstdlib/srand/time returns a number depending on the time, which makes it more random because you don't know when exactly someone will run the program. another common way is to seed the mouse position.
• 1

## C

122,620 followers