# Srand () w/ range

This is a discussion on Srand () w/ range within the C Programming forums, part of the General Programming Boards category; Code: srand(time(NULL)); range = (15-9) + 1; printf(" %d", rand() % range + 9); That code was for a range ...

1. ## 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.

2. >The range I'm trying to get is -5 to 14.
Code:
```     srand(time(NULL));
range = (14 - -5) + 1;
printf(" %d",   rand() % range - 5);```

3. Do it after, since rand()'s return value is 0 to RAND_MAX.

nevermind...[/edit]

4. 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!

5. I guess to generalize you could write:
Code:
`num = (rand() &#37; (upper - lower + 1)) + lower`

6. 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

7. Well you've got 7 different numbers so:
Code:
`num = 3 * (rand() &#37; 7) + lower;`
lower would be -5 in this case.

8. Starting from 0,
Code:
```/* interval of 3 from 0 */
if(num &#37; 3 == 0)```
Now adjust for starting from -5

9. awesome, thanks guy ;D