Counting

Basic Algorithms
≈ 2 min read

A counter as algorithm state

In many problems, you do not need to store the matching elements themselves. It is enough to know how many times the required condition occurs. For that, use a counter variable: it starts at zero and increases each time the current element matches.

int count = 0;

for (int value : numbers) {
    if (value % 2 == 0) {
        count++;
    }
}

After the loop, count contains the number of even elements. The entire algorithm consists of just three ideas: traverse the data, test a condition, and update the counter.

You can count more than elements

A counter is useful anywhere an event can be expressed as a condition. For example, you can count positive numbers, strings of a certain length, values crossing a given threshold, or the number of digits in a number.

Sometimes it is convenient to maintain several counters during the same pass. For example, you can count positive and negative values separately.

int positive = 0;
int negative = 0;

for (int value : numbers) {
    if (value > 0) {
        positive++;
    } else if (value < 0) {
        negative++;
    }
}

Zero deliberately belongs to neither group here. The problem statement determines which cases should be included and which counters are actually needed.

A common mistake: the wrong initial value

If nothing has been found before processing begins, the count is zero. That is why a normal counter is almost always initialized with 0. Starting at one would mean counting an event that has not happened yet.

First define what counts as one event. If you cannot describe the condition for increasing the counter in one simple sentence, it is worth revisiting the problem statement before writing the loop.