Question 8-4

[15 pts] Write a class method named mode that takes an array of ints as a parameter and returns the integer that occurs in the array most frequently. For example, the following code fragment that uses your mode method should print 23.

int[] a = { 23, 34, 45, 23, 0, 23 };
IO.println(mode(a));
Your method should not call any other methods to accomplish this. It will need more than one loop to count the number of occurrences of each number in the array.

Solution

public static int mode(int[] data) {
    int maxcount = 0;
    int maxnum = 0;
    for(int i = 0; i < data.length; i++) {
        int count = 0;
        for(int j = 0; j < data.length; j++) {
            if(data[j] == data[i]) count++;
        }
        if(count > maxcount) {
            maxcount = count;
            maxnum = data[i];
        }
    }
    return maxnum;
}

Back to 8:00 Quiz 8