Counting Occurrences in an Array

In this lesson, let's find the number of times a given value occurs in an array.

We'll cover the following

Problem statement

The example in the previous lesson formed in an array, ageList, of positive integers that are the ages of the people in a group. The variable ageCount contains the number of ages in the array, and we know that ageCount does not exceed 50, the array’s capacity. Suppose that we now want to know how many people in our group are 18 years old.

Solution

To count the number of times a given value occurs in an array, we compare it to every entry in the array. Here we compare 18 to every age in ageList. We use a loop to cycle through the array’s indices from 0 to ageCount – 1. If index represents these index values, we must compare 18 with ageList[index] for each value of index. Each time we find a match, we increment a counter. When the loop ends, the value of the counter is the desired result.

Here is a for loop that performs this task:

Get hands-on with 1200+ tech skills courses.