Iterating Through 1D Array

Now that we know what an array is and what it contains, let's see how we can apply loops to help us accomplish tasks with arrays. For example, you want to know the sum of all the elements in an array. Instead of summing each element together in your head, you can write a for loop to do the work for you. Check out the code below for an example.

Iteration1DExample.java
package exlcode;

public class Iteration1DExample {

public static int[] exampleVariableOne = {0, 1, 2, 3, 4, 5, 6, 7, 8};
public static int sum = 0;

public static void main(String[] args) {
// for loops are the most common method when
// iterating through an 1D array
for (int count = 0; count < exampleVariableOne.length; count++) {
// add each element to sum
sum += exampleVariableOne[count];
}
// print the total sum of all the elements in the array
System.out.println(sum);
}
}

The for statement has the condition count<exampleVariableOne.length, which makes sure that every element in the array is added to sum before the for loop is terminated. Why do we use '<'? Because the last index of the array is always array.length-1, so count cannot be equal to or greater than exampleVariableOne.length. If we do not specify this, a runtime error may occur.

The for loop above is a prime example of the loops used when dealing with one-dimensional arrays. As you master using a for loop and accessing the elements in an array, you will start writing more complicated programs that deal with large amounts of data. Being able to iterate through arrays using loops is important because arrays cannot be directly printed to the console. System.out.println(arrayname) won't work.

Application Question

#!exl::repl('index.prob.repl.yaml')