1. ## random number problems

ok, I feel like what I'm missing is something simple but i"m not seeing it, I'm trying to write a program that generates a random number between 1 and 2 and do that x number of times where x is the input from the user. The way this works is it keeps printing the same number over and over. Like if it's 2 then it shows that 2 is generated each time.

Code:
```int twoside(void)
{
int i, n;
n = 0;

do{
srand(time(NULL));
i = (rand() % (2) + 1);

printf("The number rolled is: %d\n", i);

n++;

}while (n < num); // num is user input for number of times the number is generated.

return i;
}``` 2. Call srand() just once, not every iteration through the loop.

Edit: When I say just once, it should be just once in the entire program, not just in the function, since time_t typically has 1 second resolution (not guaranteed though) so if you had srand() in the function, and called the function more than once in a second, you would get the same sequence of values in the successive function calls.

http://en.wikipedia.org/wiki/Time_t 3. Code:
```int GetRandomValues(int nTimes, int low, int high)
{
if(nTimes)
{
int i = 0;
int randomNumber = 0;
int width = high - low + 1;
if(width < 0)
width = -width;
//Initialise generator.
srand(time(NULL));

for(i = 0; i < nTimes; randomNumber = (rand() % width) + low, printf("Random Number Generated: %d\n", randomNumber), i++);
if(i == nTimes)
return 0;
else
{
printf("Error in loop.\n");
return -1;
}
}
else
{
printf("Please insure that we have a non zero number of times.\n");
return -2;
}
}```
The above code generates nTimes the numbers you want. Check it and make one for yourself. If you encounted any problems tell us.

In main() call the fucntion like that:

GetRandomValues(10, 1,2);

Happy Codings.    4. It looks like your num is a global variable. Avoid using global, they are not good. Send them as a paramter which makes it more neater.

ssharish2005 Popular pages Recent additions 