Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

canada eh

macrumors regular
Original poster
Dec 22, 2009
117
0
Barrie, Ontario
Hi, I am trying to find the mode in an array. Whenever I run the following code the mode only displays 0. The original array is ( mark[] ) it is only configured for a maximum of 10 numbers. Could some one point out to me where I went wrong?

Thanks :)

Code:
// create array of tallies, all initialized to zero
        int[] tally = new int[101];
        for (int i = 0; i < 10; i++) {
            tally[i] = 0;
        }

        // for each array entry, increment corresponding tally box
        for (int i = 0; i < 10; i++) {
            int value = (int) mark[i];
            tally[value]++;
        }

        // now find the index of the largest tally - this is the mode
        int maxIndex = 0;
        for (int i = 1; i < 10; i++) {
            if (tally[i] > tally[maxIndex]) {
                maxIndex = i;
            }
        }
        
        System.out.println("Mode is: "+ maxIndex);
 
tally has 101 elements. Based on this, I'm guessing mark can only have values from 0-100. In all of your loops, you only initialize, test, etc elements 0-9. Thi is correct for the second loop, but wrong for the first an third. Do you have any marks between 1-10 in that array? More of them than you have 0? If not, you're getting the result you're looking for, the most common element between 0-10.

-Lee
 
The whole program is a mark-book sort of deal where you enter in the grade as a percentage for 10 students (the limit of mark[]) and the program will calculate the mode out of the 10 grades entered by the user. the percentage is between 0 and 100%. Which would be the most occurring number between 0 and 100 is what I'm looking for.
 
Right, I gathered that. So when you loop over your tally array, 0 to 100. When you loop over your marks array, 0 to 9.

-Lee
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.