-2

I would like to get a random integer between 1 and 10 in C++ using the least amount of code possible, with the start and stop values being inclusive.

I'm aware of the rand() function, but how can I use it to get an integer in this range?

Thank you!

Ben Soyka
  • 816
  • 10
  • 25

2 Answers2

1

You can generate a random integer between 1 and 10 (inclusive) with this piece of code

int i = rand()%10+1;

//rand()%10 get a random int between 0 to 9
//and what you should do next is +1
Matisse
  • 26
  • 3
  • 1
    Also mention the fact that rand() will give the same number no matter how many times you recompile the program – Hemil Mar 10 '19 at 05:48
0

you can check out this article which details precisely how to obtain random integers.

int i = rand()%8+2;

should give you random integers between 1 and 10 both exclusive

TheRealOrange
  • 115
  • 1
  • 1
  • 9