I have to loop through 1 <= i <= 20
and every time I mod any i, I want to get a value between 1,2,3
. Sorry I have not found any useful resources online. That's why I posted it here. Thanks in advance.
Asked
Active
Viewed 445 times
-2

Maisha
- 45
- 1
- 1
- 8
-
Do you know what mod does? Do you know how to get any interesting result applying it to `i`? – Beta Jan 13 '22 at 05:06
-
Use the modulo operator, e.g. index = (i % 3)+1; (https://www.learncpp.com/cpp-tutorial/arithmetic-operators/) – Pepijn Kramer Jan 13 '22 at 05:06
1 Answers
4
In C++ the %
sign acts as the remainder operator.
If you do
i % 3;
The possible values are 0
, 1
, and 2
.
Using that as a starting point, we can shift by 1
:
(i % 3) + 1;
The possible values are now 1
, 2
, and 3
.

Nathan Pierson
- 5,461
- 1
- 12
- 30
-
1Minor point: `%` is the **remainder** operator, not the modulo operator. Remainders can be negative. – Pete Becker Jan 13 '22 at 14:09