Looping through Part of an ArrayΒΆ

You don’t have to loop through all of the elements of an array. You can loop through just some of the elements of an array using a for loop. The following code doubles the first five elements in an array. Notice that it uses a complex conditional (&&) on line 12 to make sure that the loop doesn’t go beyond the bounds of the array.

You can even start in the middle and loop through the rest of the array. Does this work for arrays that have an even number of elements? Does it work for arrays that have an odd number of elements? Modify the main code below to test with both arrays with an even number of items and an odd number.

Mixed up programs

        7-5-3: The following program has the correct code to reverse the elements in an array, a,  but the code is mixed up.  Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.

public void reverse() { --- int temp = 0; int half = a.length / 2; int max = a.length - 1; for (int i = 0; i < half; i++) { --- temp = a[i]; --- a[i] = a[max - i]; --- a[max - i] = temp; --- } // end for --- } // end method
        7-5-4: The following program has the correct code to return the average of the first 3 items in the array a, but the code is mixed up.  Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.

public double avg3() { --- double total = 0; for (int i = 0; i < a.length && i < 3; i++) { --- total = total + a[i]; --- } // end for return total / 3; --- } // end method
Next Section - Things to Watch For When Looping Through an Array