+2 votes
in Programming Languages by (11.1k points)

I am trying to generate random number using rand() function, but everytime it generates the same number. I am using gcc to compile my code on ubuntu. How can I get different numbers? My code is as follows:

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

int main(){
        int i = rand();
        printf ("Random number is %d\n",i);
        return 0;
}

1 Answer

0 votes
by (15.8k points)

You need to use a seed to get different values. Use srand() function before rand() function so that the random function can use different seed values. If you do not explicitly use srand() function, rand() function uses srand(1).  You can use time(0) [current time] to generate the seed value. Check the following example.

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

int main(){

        srand(time(0)); //set seed value

        int i = rand();

        printf ("Random number is %d\n",i);

        return 0;

}

...