Problem making a wrap around loop with modulo

modulo is simple, it takes the remainder of a division

for (int i=0; i < 16; i++) 
  println (i+" -> " + i%5); //or k=i%5;

gives you


0 -> 0
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 0
6 -> 1
7 -> 2
8 -> 3
9 -> 4
10 -> 0
11 -> 1
12 -> 2
13 -> 3
14 -> 4
15 -> 0

So you can use it when your array has only 5 elements (index 2nd column), but your for loop is longer than 5 (first column above).

You can also write

k++;
if(k>4) i=0;

which I personally find much better to read

Chrisir

1 Like