Looping Through Arrays
An index loop can visit every array element and still expose the position of each value.
The standard boundary is i < array.length. The last valid index is one less than the length.
Visit every index
public class Main {
public static void main(String[] args) {
int[] scores = {91, 84, 77, 88};
int total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
System.out.println(total);
}
}
Output:
340
The loop visits each valid index and adds the stored score to total.
Using i <= array.length runs once too often and throws ArrayIndexOutOfBoundsException.
Use the index in the loop to add every price to the total.