Next: None. Up: Arrays. Previous: Accessing array elements.


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?


Next: None. Up: Arrays. Previous: Accessing array elements.