Unit 4 Cycle 1 Day 25: 2D Array: Counting Specific Values

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

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.

int[][] grid = {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}; int count = 0; for (int[] row : grid) { for (int val : row) { if (val == 1) { count++; } } } System.out.println(count);

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.

Review this topic: Section 4.11 — 2D Array Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

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