Keavon
Keavon

Reputation: 7532

For loop with if(array[i + 1]) goes out of array bounds; how to loop to beginning?

I have an array and a for loop an if statement that checks for i + 1. However, on the last iteration of the loop, the array goes out of bounds. I want to loop back to the beginning of the array when this happens. What is the best way to loop around back to array[0]? Here's my code:

int[] array = new int[5];
array[0] = new int(5);
array[1] = new int(7);
array[2] = new int(3);
array[3] = new int(1);
array[4] = new int(9);

for (int i = 0; i < array.Length; i++)
{
    if (array[i + 1] != 0)
        // Do something (obviously in this example, this will always occur)
    {
}

I can do the following, but it requires me to duplicate my code (and my current code inside this is huge). Is there a better way to do the following?

int[] array = new int[5];
array[0] = new int(5);
array[1] = new int(7);
array[2] = new int(3);
array[3] = new int(1);
array[4] = new int(9);

for (int i = 0; i < array.Length; i++)
{
    if (i != array.Length - 1)
    {
        if (array[i + 1] != 0)
            // Do something (obviously in this example, this will always occur)
        {
    }
    else
    {
        if (array[0] != 0)
            // Do something (obviously in this example, this will always occur)
        {
    }
}

Upvotes: 1

Views: 608

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1063664

array[(i + 1) % array.Length]

Should do the trick without too much pain.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

for (int i = 0; i < array.Length; i++)
{
    if ((i + 1 < array.Length && array[i + 1] != 0) || (i + 1 == array.Length && array[0] != 0))
        // Do something (obviously in this example, this will always occur)
    {
}

Upvotes: 1

nolegs
nolegs

Reputation: 608

Use modulus:

if(array[(i+1) % array.Length] != 0) {...}

This will basically subtract array.Length from (i+1) until (i+1) < array.Length

Upvotes: 6

Related Questions