I am trying to generate a random number, but it should not be a particular number. So i am passing the number which should not be the random number and the range in which it has to be generated to the function, and i am reinvoking the function if the random number generated is the number, which should not be generated, so this is taking a long time and resulting in termination of my program. I am using the following code, let me know how effecient i can generate the random number without waiting for long or even without reinvoking the function.

here rank1 is the number passed to it, which should not be generated and size1 is the number, denoting the range of the maximum accepted value

int rgenerator(int rank1, int size1)

{

int iseed, k;
time_t seconds;
time(&seconds); 
iseed=(unsigned int) seconds;


srand(iseed);



k=rand()%size1;

if(k!=rank1)
return k;
else 
rgenerator(rank1,size1);

}

Recommended Answers

All 3 Replies

1) Never call srand() where you need a random number. Call it once at the beginning of the program only.
2) use a while loop instead of a recursive function.

But this is not working correctly is this include any header file or main function

#include <stdlib.h>

Hope this help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.