# Srand () w/ range

• 10-20-2007
xsbinary
Srand () w/ range
Code:

```    srand(time(NULL));     range = (15-9) + 1;     printf(" %d",  rand() % range + 9);```
That code was for a range between 9 to 15, but I'm having problems with getting it into the negative range. The range I'm trying to get is -5 to 14.

Any help is appreciated, thank you in advance.
• 10-20-2007
swoopy
>The range I'm trying to get is -5 to 14.
Code:

```    srand(time(NULL));     range = (14 - -5) + 1;     printf(" %d",  rand() % range - 5);```
• 10-20-2007
zacs7
Do it after, since rand()'s return value is 0 to RAND_MAX.

nevermind...[/edit]
• 10-20-2007
xsbinary
awesome, thanks swoopy. I wasn't sure if 14 - - 5 would work, because i would assume it be 20. but then writing out the number &#37; 20 - 5 would work as well. Thanks!
• 10-20-2007
swoopy
I guess to generalize you could write:
Code:

`num = (rand() &#37; (upper - lower + 1)) + lower`
• 10-20-2007
robwhit
• 10-20-2007
xsbinary
I want to be able to expand what we're doing. how would I go about only choosing intervals randomly from the range?
So between -5 to 14 but intervals of 3. Selecting only the possibilities of :
-5, -2, 1, 4, 7, 10, 13
• 10-20-2007
swoopy
Well you've got 7 different numbers so:
Code:

`num = 3 * (rand() &#37; 7) + lower;`
lower would be -5 in this case.
• 10-20-2007
zacs7
Starting from 0,
Code:

```/* interval of 3 from 0 */ if(num &#37; 3 == 0)```
Now adjust for starting from -5 ;)
• 10-21-2007
xsbinary
awesome, thanks guy ;D