Course contentsShow
← C
Lesson 317 of 1,2194. Control FlowFree lesson

The Counter pattern (counting occurrences)

The Counter pattern (counting occurrences)

What you'll learn: How to use a dedicated variable to track how many times a specific event occurs within a loop.

The basic idea

Imagine you are standing at the entrance of a stadium with a handheld clicker. Every time a person wearing a red shirt walks through the gate, you press the button. You don't care about the total number of people, nor do you care about blue or green shirts—you are only interested in one specific event. By the end of the day, the number on your clicker represents the total count of red shirts.

In C programming, the Counter pattern works exactly like that handheld clicker. You initialize a variable to zero, loop through a set of data, and increment that variable only when a specific condition is met.

Building the clicker

To implement this, you need three ingredients:

  1. A counter variable initialized to 0 (this is your clicker).
  2. A loop to examine every item in a collection.
  3. An if statement to check if the current item matches your criteria.

Without initializing the variable to zero, your "clicker" starts at a random number (garbage value), which will make your final count incorrect.

The pattern in action

In this example, we will count how many times the number 7 appears in a list of data.

#include <stdio.h>

int main() {
    int numbers[] = {7, 3, 7, 2, 9, 7, 5};
    int length = 7;
    
    // 1. Initialize the counter to zero
    int count = 0;

    for (int i = 0; i < length; i++) {
        // 2. Check the condition
        if (numbers[i] == 7) {
            // 3. Increment the counter
            count++;
        }
    }

    printf("The number 7 appeared %d times.\n", count);
    return 0;
}

Why this matters

The counter pattern is the foundation for more complex logic. You might use it to count failed login attempts, track how many enemies are left on a game level, or calculate an average (since an average is just a total sum divided by a count). The most common mistake is forgetting to set the counter to 0 at the very start, so always double-check your initialization!

Key takeaway

A counter is a variable that starts at zero and increments by one inside a loop whenever a specific condition is true.