Skip to main content
Engineering LibreTexts

16.8: Traverse and Count

  • Page ID
    18917
  • If these values were exam scores – and they would be pretty bad exam scores – the teacher might present them to the class in the form of a histogram. In statistics, a histogram is a set of counters that keeps track of the number of times each value appears.

    For exam scores, we might have ten counters to keep track of how many students scored in the 90s, the 80s, etc. To do that, we can traverse the array and count the number of elements that fall in a given range.

    The following method takes an array and two integers, low and high. It returns the number of elements that fall in the range from low to high.

    public static int inRange(int[] a, int low, int high) {
        int count = 0;
        for (int i = 0; i < a.length; i++) {
            if (a[i] >= low && a[i] < high) {
                count++;
            }
        }
        return count;
    }
    

    This pattern should look familiar: it is another reduce operation. Notice that low is included in the range (>=), but high is excluded (<). This detail keeps us from counting any scores twice.

    Now we can count the number of scores in each grade range:

    int[] scores = randomArray(30);
    int a = inRange(scores, 90, 100);
    int b = inRange(scores, 80, 90);
    int c = inRange(scores, 70, 80);
    int d = inRange(scores, 60, 70);
    int f = inRange(scores, 0, 60);
    
    • Was this article helpful?