I have a semaphore variable with 5 states.
I can increase the state using this cicle
X = (X + 1) % 5
For X = {0, 1, 2, 3, 4} generate {1, 2, 3, 4, 0}.
But if I try go in the other direction decreasing the state, doesn't bring the right result.
X = (X - 1) % 5
For X = {0, 1, 2, 3, 4} generate {-1, 0, 1, 2, 3} insted of {4, 0, 1, 2, 3}
For example in excel if you try =MOD(-1;5)
you get 4.
Instead of
use
which is the short form of
or generally
This ensures that the argument in
()
is always positive - so the division remainder stays also positive.