By Dante de la Fuente


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?

2 comments

@CaitLAN Jenner 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.

Related Questions

Sponsored Content

1 Answered Questions

8 Answered Questions

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

  • 2015-06-13 17:15:39
  • badmad
  • 41020 View
  • 303 Score
  • 8 Answer
  • Tags:   c random

2 Answered Questions

[SOLVED] C rand() dice issue

  • 2016-10-16 16:38:21
  • Piet
  • 508 View
  • 4 Score
  • 2 Answer
  • Tags:   c random modulus

2 Answered Questions

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

Sponsored Content