Next: Arrays holding records. Up: Array examples. Previous: Simple tasks.


Finding the mode

You won't always want to go through the array step by step. Sometimes you'll go through the array more or less randomly.

Consider, for example, the following program to find the most commonly occurring test score. To do this, we'll maintain an array saying how many times each test score has occurred.

public class FindMode {
    public static void main(String[] args) {
        int[] tally = new int[101];
        for(int i = 0; i < tally.length; i++) tally[i] = 0;

        IO.print("How many students? ");
        int num = IO.readInt();
        IO.println("Type 'em.");
        for(int i = 0; i < num; i++) tally[IO.readInt()]++;

        int max_i = 0;
        for(int i = 1; i < num; i++) {
            if(tally[i] > tally[max_i]) max_i = i;
        }
        IO.print("Mode is " + max_i);
    }
}
The first and third for loops here are doing using the sequential access we've seen so far. The middle one jumps all over the tally array, based on which score it is currently reading.


Next: Arrays holding records. Up: Array examples. Previous: Simple tasks.