Please enable JavaScript to use CodeHS

Chapter 6

Arrays

6.2 Traversing Arrays

Arrays are utilized for many operations in various programs. Since arrays store data in order, you can iterate through them to access this data. Let’s say you are creating an online store that sells oranges. You would want to store the customer orders in an array so you can honor the first orders before the orders that come later.

Accessing the Array

Let’s say you have an array that stores the order data from your market. Here is the array:

Index: 0 1 2 3 4 5
Orders: 10 Oranges 3 Oranges 6 Oranges 4 Oranges 5 Oranges 1 Orange

In Java the array will look like this:

int[] orangeOrders = {10, 3, 6, 4, 5, 1};
Plain text

Individual elements can be accessed by using the [] notation:

int orderOne = orangeOrders[0];  //returns 10 to orderOne
Plain text

Since this list of orders is fairly small, it’s easy to access the individual orders that are being made, but oftentimes, arrays can have hundreds, thousands, or even millions of values. How is it possible to access all values when it’s not clear where a specific value might be stored? There needs to be a systematic way to access all of these values! Luckily, iteration, or traversing, an array can provide a simple solution.

Determining Array Size

In order to iterate through the items in an array, it’s absolutely necessary to know how many elements there are in the array - otherwise, how would you know how many elements you need to search through?

Finding the size of an array is done by using the keyword .length. .length returns the current size of an array. An array with six values is considered an array of length 6. The length of an array corresponds to the number of elements in an array, not the last index value in an array.

If you recall, arrays start at index 0 - an array with six elements will start at 0 and end at index 5:

Index: 0 1 2 3 4 5
Orders: 10 Oranges 3 Oranges 6 Oranges 4 Oranges 5 Oranges 1 Orange

Iterating over an Array

Iterating over an array requires the use of a for or while loop:

for(int i = 0; i < orangeOrders.length; i++)
{
   // This prints out the ith element!
   System.out.println(orangeOrders[i]);
}
Plain text

This for loop iterates through every value in the orangeOrders list, and prints out the value at every index.

Notice that the for loop starts at the first element (zero) and ends at the last element (array.length - 1). The for loop is set to i < orangeOrders.length, so that the greatest value of i will always be one less than the length of the array. Therefore, the last index in an array will always be array.length - 1.

Each time through the loop, the value of i accesses the element at index i. This simple for loop is able to loop through the array, regardless of how many items there are in the array.

This traversal can also be written using a while loop:

int index = 0;
while(index < orangeOrders.length)
{
   System.out.println(orangeOrders[index]);
   index++;
}
Plain text

Notice that the variable index is outside of the while loop. This ensures that the variable index isn’t reset to 0 every time the while loop starts a new iteration. The value of index is increased by one at the end of the while loop, ensuring that the next index in the array will be accessed.

When developing iterative programs for use with arrays, it’s important to pay attention to which values are being set as the starting and ending indices. A common mistake programmers make is setting the ending index to the length of the array, not the last index value:

int index = 0;
while (index <=orangeOrders.length)
{
   System.out. println(orangeOrders[index]);
   index++;
}
Plain text

In this example, the final value of index will be 6, even though the last index in orangeOrders is 5. As a result, this program will lead to an ArrayIndexOutOfBoundsError. This type of error is referred to as an “off by one” error, as the program iterates one too many times over the array.

Iterating Over An Array - For Loop

Iterating Over An Array - While Loop

Array Out of Bounds

Finding a Target Value

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    What is the output after this code snippet runs?

    double[] prices = {3.45, 1.00, 2.25, 5.22, 4.50};
    
    for (int i = 0; i < prices.length; i += 2)
    {
           System.out.println(scores[i] = prices[i]  -  1);
    }
    Java

Exercise: Print Even Array Indices

Here we have a program that creates an integer array. Fill in the method printEvenIndices() to print out just the elements stored at the odd indices of the array.

For example, the following code:

int[] arr = new int[] {10, 20, 30, 40};
printEvenIndices(arr);
Plain text

Should print out:

10
30
Plain text

Because the even indices (including 0) in arr are 0 and 2, and index 0 stores the value 10 and index 2 stores the value 30.