Traverse an array in reverse using modulus.

Traverse an array in reverse using modulus.

Have you ever needed to traverse an array in reverse? Traversing an array is pretty easy to do using a “for” loop or even a “foreach” loop. The issue I came up against was I didn’t need to traverse an array in a loop I needed to access the data directly in reverse using an index value. Then either increment or decrement the value based on a button click.

To traverse an array is easy and is pretty common and not going to win you any awards. You can simply use modulus like this:

This code will move through the array until it reaches the end and then start over. But what if you want to do this in reverse. This is what I found was the easiest.

The later adds the length of the array back into the equation. This makes sure that if the index is negative it will become positive again. Then the modulus of the whole thing will give you the correct index again.

There are several other examples of this code all over the internet and you should check them out to make the best decision for your application. Using Modulo in this way to traverse an array in reverse adds some complexity to your code and not everyone will know why or what you are doing so be careful and as always comment your code for the next guy. Even if the next guy is you.