Small Steps III — Thinking with Programs

Counting matching values

Count values that meet a condition.

What you will learn

To count matches, add 1 only when you encounter an element that meets the condition.

Try it

Example · example2.cpp
int count_even(Array<int> numbers)
{
    int count = 0;

    for (int i = 0; i < numbers.length(); i = i + 1)
        if (numbers[i] % 2 == 0)
            count = count + 1;

    return count;
}

void small_main()
{
    Array<int> numbers = {3, 8, 4, 7, 10};
    print("Even: ", count_even(numbers));
}

numbers[i] % 2 == 0 asks whether division by 2 has remainder 0: whether the number is even. 8, 4, and 10 match, producing Even: 3. Zero also meets this condition.

count_even takes an array parameter. Here, it receives a copy of an Array<int> value; later lessons on references show how to avoid copying.

Exercise

Count and print how many values in the Array are greater than 0.

Exercise starter · exercise2_starter.cpp
void small_main()
{
    Array<int> numbers = {-2, 5, 0, 8, -1, 3};
    int count = 0;

    // Count positive values.

    print(count);
}

Hint

Check numbers[i] > 0 for each value and increase count by 1 when true.

show solution
void small_main()
{
    Array<int> numbers = {-2, 5, 0, 8, -1, 3};
    int count = 0;

    for (int i = 0; i < numbers.length(); i = i + 1)
        if (numbers[i] > 0)
            count = count + 1;

    print(count);
}
← Previous lessonNext lesson →