#### [SOLVED] Problems with C rand()

I'm new to C. I just came across the rand() function. The book states that using rand() returns a random number from 0 to 32767. It also states that you can narrow the random numbers by using % (modulus operator) to do so. Here is an example: the following expression puts a random number from 1 to 6 in the variable dice

``````dice = (rand() % 6) + 1;
``````

I’m wondering why you can’t use

``````dice = (rand() % 7);
``````

Won’t it do the same thing?

#### @h0r53 2019-11-08 14:28:05

This is more of a math question than a C question. The answer lies in modulo arithmetic. Any number `x modulo n` equals 0 if `n` divides `x` evenly. In fact, the modulo operator returns the remainder of integer division. Therefore the range is from `0` to `n - 1`. So if you want a random number 1-6 you need to perform `(rand() % 6) + 1`, since `rand() % 6` gives you something in the range of 0-5. Simply doing `rand() % 7` gives you the range 0-6, increasing the upper bound, not the lower bound.

#### @molbdnilo 2019-11-08 14:28:28

`rand() % 6` is a number in the interval 0-5.
If you add one to any number in that interval, you get a number in the interval 1-6.

On the other hand, `rand() % 7` is a number in the interval 0-6.

### [SOLVED] Why does rand() + rand() produce negative numbers?

• 2015-06-13 17:15:39
• 41616 View
• 302 Score
• Tags:   c random

### [SOLVED] C rand() dice issue

• 2016-10-16 16:38:21
• Piet
• 559 View
• 4 Score