Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I increment and decrement an integer with the modulo operator

I am trying to increment an integer based on a click. How the click happens does not matter so I'll stick to the logic. I am doing this in Java but the logic should be the same all around.

int index = 0;

// then within the click event
//arrySize holds the size() of an ArrayList which is 10

index = (index + 1) % arrySize;

With this logic, every time the user clicks, index will increment by 1. Then its modulo of arrySize causes index to go back to 0 when index matches arrySize

(10 % 10 would make the index go back to 0) Which is great because it's kind of like a loop that goes from 0 to 10 then back to 0 and never over 10.

I am trying to do the same logic but backwards where based on the click the number will decrement and get to 0 then goes back to the arrySize instead of -1

How can I achieve this logic?

like image 828
Lucas Santos Avatar asked Dec 31 '15 20:12

Lucas Santos


1 Answers

(index + arraySize - 1) % arraySize

Does what you want.

like image 106
Louis Wasserman Avatar answered Sep 22 '22 10:09

Louis Wasserman