# Thread: SRAND in a range

1. ## SRAND in a range

How do you use SRAND to generate random numbers in a range of say 9 to 15.

I have tried all methods, see C Programming notes, but no luck.

2. Hi

u'll need functions like:

- srand()
- time()
- rand()

...

Give it a try!
aloa

cody

P.S.: Plz don't crosspost, thnx

3. ## I know the header library, but,.....

I know how to do it from say 1 - 100 but not in a range.

Here is my code for 1 -100

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

int main(void)
{
int i;
time_t t;

srand((unsigned) time(&t));

for(i=0; i<10; i++)
printf("%d\n", rand() % 100);
return 0;
}

But how do I do it say numbers from 10 - 25?
Thankyou

4. there is good info on this in the faq.
dont crosspost its annoying.

first seed the random number generator. As it is a pseudorandom number generator the same seed will always produce the same sequence of random numbers. This is normally overcome by seeding with the system time. This only has to be done once.

srand((unsigned)time(null));

now to get a range of numbers use rand() coupled with modulus operator...

for instance range 9-15

so in general you want to modulus by (highrange-lowrange)+1.
i.e. 15-9+1=7

so rand()%7 gives us random numbers in the range 0-6.
to convert this to range 9-15 just add 9.
therefore random numbers in range 9-15 can be got like this...
rand()%7 + 9;

got it now?