4

Possible Duplicate:
Generate Random numbers uniformly over entire range
How to use rand function to

Could anyone tell me how to use the rand() function in C programming with 1 = min and
7 = max, 1 and 7 included.

Thanks

Community
  • 1
  • 1
Slrs
  • 105
  • 1
  • 3
  • 11

2 Answers2

16

This will do what you want:

rand() % 7 + 1

Explanation:

  • rand() returns a random number between 0 and a large number.

  • % 7 gets the remainder after dividing by 7, which will be an integer from 0 to 6 inclusive.

  • + 1 changes the range to 1 to 7 inclusive.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
3

Use the modulo operator. It returns the remainder when dividing. Generate a number in range 0 to 6 by using rand() % 7. Add 1 to that to generate a number in range 1 to 7.

Michel
  • 2,523
  • 2
  • 17
  • 14