Session 10: Arrays

The array type (Section 5.1)
Accessing array elements
Practice
    Averaging example
    Shifting

The array type

Textbook: Section 5.1

An array is a sequence of several items. It gives us a way of having a single variable represent many similar items at once. This might, for example, be useful for representing students within a class, or components of a window, or files within a directory.

An array contains several items, all of the same type. Each item is called an element, and each element has a numeric address, called an index. The indices start at 0 and increase upward.

To declare an array variable, name the type of the array elements, followed by a pair of empty brackets, followed by the variable name.

int[] scores;
This creates a variable scores, which can hold an array of integers. Note that it doesn't actually hold an array yet - it just has the ability to hold an array. In this respect, arrays are like objects: We must explicitly create one before we use it. (Actually, the analogy extends further, as we will see later.)

Before you use an array you must create explicitly create it. We do this using the new keyword, as we did with objects.

scores = new int[30];
This makes scores point to an array of 30 integers.

As before, we can combine the variable declaration and initialization into one step.

int[] scores = new int[30];

If we happen to know exactly what we want in the array, we can list the items explicitly for initialization.

double[] pows = { 1.0, 0.5, 0.25, 0.125, 0.0625, 0.03125 };
This creates an array of six items, holding the named values.

Accessing array elements

To use arrays, you can use the subscript operator, a set of brackets. Into the brackets go the index of the element we're trying to access. For example, we might do the following.

IO.println(pows[2] + pows[4]);
In this example, we load array elements 2 and 4 (the third and fifth elements, 0.25 and 0.0625), add them together, and finally print the sum (0.3125).

We can also use array indices on the left-hand side of an assignment operator to change the value at a location in the array.

scores[0] = 23;

Frequently, when you access an array, you'll want to use a for loop to go through all the possible array elements. For example, the following code block would set all the array elements of scores to be 100.

for(int i = 0; i < scores.length; i++) {
    scores[i] = 100;
}
This illustrates the use of length, an instance variable for the array which represents how many array elements it has (30). For each of the integers i from 0 up to scores.length, we set array element i to be 100.

Practice

Averaging example

We're going to write a program to get a list of numbers from the user and determine their average.

import csbsju.cs160.*;

public class ArrayAverage {
    public static void run() {
        // determine how many number we have to process
        IO.print("How many numbers? ");
        int n = IO.readInt();

        // load them into the array
        int[] data = new int[n];
        IO.print("Type the numbers.");
        for(int i = 0; i < data.length; i++) {
            data[i] = IO.readInt();
        }

        // determine the sum
        int sum = 0;
        for(int i = 0; i < data.length; i++) {
            sum += data[i];
        }

        // display average
        double avg = 1.0 * sum / data.length;
        IO.println("Average: " + avg);
    }
}

If we to run this program, we'd see the following interaction with the user.

How many numbers? 4
Type the numbers.
75
25
40
60
Average: 50.0

In fact, this example is somewhat contrived: You could accomplish it without arrays, by keeping a running sum as we read in the numbers. But then that wouldn't help you understand arrays!

Shifting

Suppose that we want to shift the elements left one spot. For example, if the array was holding { 75, 25, 40, 60 }, we want to change it so that it is now holding { 25, 40, 60, 0 }. (Note how we put 0 into the newly empty spot.) How would you accomplish this?

Suppose that instead you wanted to shift the array right: Starting with { 75, 25, 40, 60 }, we want to get to { 0, 75, 25, 40 }. How would you modify the left-shifting code to accomplish right-shifting instead?