Reputation: 910
Let's say I've an array of 4 items.
When I access the first index, I would also like to access an offset of -1 (in this case, it would loop to 3)
for(int i = 0; i < array.Length; i++)
{
int item = array[i];
int offset = 0;
if (i == 0)
{
offset = array.Length -1;
}
else
{
offset = i -1;
}
int offsetItem = array[offset];
}
Is there a more elegant way of achieving this? I keep thinking of using the modulo operator, but I don't understand it well enough to know if its the solution.
Upvotes: 2
Views: 516
Reputation: 726589
Yes, there is. Add the length of the array to the index, and use remainder operator, like this:
int offset = (i-1+array.Length) % array.Length;
Upvotes: 1
Reputation:
you cannot define variable i within the loop as i has already been defined.
for(int i = 0; i < array.Length; i++) {
int j = array[i];
int offset = (j == 0)?(array.Length -1):( i -1);
int offsetItem = array[offset];
}
Upvotes: 2