comment 0

Traverse an array in reverse using modulus.

Have you ever needed to traverse an array in a reverse¬†fashion? 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:

[code lang=”csharp” gutter=”true”]
index = index % myArray.Length;

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.

[code lang=”csharp”]
index = (index % myArray.Length + myArray.Length) % myArray.Length;

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.

I cannot take all the credit for this here is the source of my code.

Leave a Reply

Your email address will not be published. Required fields are marked *