# Thread: Can someone help me with code to generate random numbers in a range of say 50-85?

1. ## Can someone help me with code to generate random numbers in a range of say 50-85?

How do I write simple code to generate random numbers in a range?

2. Just use rand() and then add the amount (50 in this case) you want the range to start at.

--Garfield

3. n = 50 + rand() % (85-50+1);

NOTE: rand() function is pseudo random, you may seed the rand() function using srand() function something like this

srand(time(NULL));
n=50+rand()%(85-50+1);

correct me if im wrong. as it has been a while since I used this function.

Best of Luck

4. What do you mean, "seed the rand() function"?

5. The random function doesn't just pick a number out of thin air, it has to perform some math on the currently seed, and generally it then replaces it's seed with the generated number.

So... if the user knows what the seed is, then all of a sudden your random numbers ain't so random anymore, so you need a random seed. Obviously, you can't use the rand function for this. As far as I know, there are two good ways to generate numbers 'random enough' to be seed values. One is time, and the other is temperature.

6. hmmm...that makes sense.

--Garfield

7. Code:
```#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

int main ()
{
int i;
printf ("INT_MAX: %d\nRAND_MAX: %d\n\n", INT_MAX, RAND_MAX);

printf ("--0--\n");
srand(0);
for (i = 0; i < 10; i++) printf ("%d ", rand());
printf ("\n\n");

printf ("--0--\n");
srand(0);
for (i = 0; i < 10; i++) printf ("%d ", rand());
printf ("\n\n");

srand(0);
rand();
srand (i = rand());
printf ("--%d--\n", i);
for (i = 0; i < 10; i++) printf ("%d ", rand());
printf ("\n\n");

srand(0);
rand();
srand (i = rand());
printf ("--%d--\n", i);
for (i = 0; i < 10; i++) printf ("%d ", rand());
printf ("\n\n");

return 0;
}```
Network issues prevent me from actually compiling this code, so feel free to add semicolons and marks of parenthesis as needed.

The point of using time to seed rand is so that the same string of random numbers cannot be generated in two different runs of the program.

8. Another thing about 'seeding' srand()

If you make multiple calls on the rand, don't seed with the same seed again. Better yet do it once on init. As the numbers are a list and PC's are so fast it may be you get the same series of 'random' numbers if you use the time.

9. Code:
```/*more appropriate */
num = (rand() %35) + 50;```

10. that max's at 84 not 85 bigtamscot.....

correctly is

num = (rand() %36) + 50;