Unit 4 Cycle 1 Day 8: Counting Matches

Unit 4 Foundation (Cycle 1) Day 8 of 28 Foundation

Counting Matches

Section 4.3 — Common Array Algorithms

Key Concept

Counting matches traverses an array and increments a counter each time an element satisfies a condition. The pattern is: initialize count = 0, loop through the array, and if (condition) count++. The condition can be any boolean expression involving the element: equality, range, divisibility, or string properties. On the AP exam, counting questions may involve complex conditions or counting elements that match a relationship with other elements (e.g., elements greater than their predecessor).

Consider the following code segment.

int[] grades = {85, 92, 78, 95, 88, 70}; int count = 0; for (int g : grades) { if (g >= 90) { count++; } } System.out.println(count);

What is printed?

Answer: (A) 2

Grades >= 90: 92 and 95. Count = 2.

Why Not the Others?

(B) 88 is less than 90, so it is not counted.

(C) Only 2 of the 6 grades meet the threshold.

(D) 6 is the total number of elements, not the count of those >= 90.

Common Mistake

The counting pattern: initialize counter to 0, increment when condition is met. This is one of the most common array algorithms on the AP exam.

AP Exam Tip

Counting pattern: int count = 0; for each element: if (condition) count++;. Make sure the condition matches exactly what is asked.

Review this topic: Section 4.3 — Common Array Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.