Sunday, February 25, 2007

In c++ u can generate random numbers by calling rand() function which is built in stdlib.h . But if u use this function without setting any seed then it gives the same random value whenever u run the code again. To solve this u can give a seed to generate random number. The best seed can be the time. A seed is set up by srand(somevalue) function. So use time u have to include time.h. Now u initialize the seed in main and use rand() fucntions else where. Now u will get different random value in different time.
A sample code can be

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

void printSomeRand()
for(int i=0;i<10;i++)
printf("%d \n",rand());///use rand to generate a random number

void main()
srand((unsigned) time(NULL)); ///give a seed, dont give seed whenever u call rand


1 Comment:

  1. Anonymous said...
    It's really hard to read the post (I don't know if you do it on the rest of the blog) because of your use of 'u' delimiting otherwise perfectly fine English.

    You might think it makes you look laid back and cool, but in fact it makes you appear just plain lazy and ignorant.

Post a Comment