Unit 4 Cycle 1 Day 25: 2D Array: Counting Specific Values
Share
2D Array: Counting Specific Values
Section 4.11 — 2D Array Algorithms
Key Concept
Counting specific values in a 2D array requires traversing every element and checking a condition. The count variable is declared before both loops and incremented inside the inner loop when the condition is met. The total number of elements checked is rows * columns. The AP exam tests counting with various conditions: specific values, values in a range, values matching a pattern, or values satisfying a relationship with their neighbors (which requires bounds checking to avoid ArrayIndexOutOfBoundsException).
Consider the following code segment.
What is printed?
Answer: (B) 5
Count 1's: Row 0 has one 1. Row 1 has three 1's. Row 2 has one 1. Total: 5.
Why Not the Others?
(A) Row 0: 1, Row 1: 3, Row 2: 1. Total is 5, not 4.
(C) 9 is the total number of elements.
(D) 3 is only the count in row 1.
Common Mistake
Enhanced for loops work with 2D arrays. The outer loop gives each row (int[]), the inner loop gives each element.
AP Exam Tip
for (int[] row : grid) iterates over rows. for (int val : row) iterates over elements in each row. Cleanest 2D traversal.