2019-11-08 14:23:12 8 Comments

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?

### Related Questions

#### Sponsored Content

#### 1 Answered Questions

#### 8 Answered Questions

#### 2 Answered Questions

#### 2 Answered Questions

### [SOLVED] Using garbage values to generate random or Pseudo-random numbers

**2013-10-26 07:56:46****xtreak****714**View**2**Score**2**Answer- Tags: c garbage-collection

## 2 comments

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