Unit 4 Cycle 2 Day 25: 2D Array: Checkerboard Pattern

Unit 4 Advanced (Cycle 2) Day 25 of 28 Advanced

2D Array: Checkerboard Pattern

Section 4.11 — 2D Array Algorithms

Key Concept

A checkerboard pattern in a 2D array alternates two values based on position. The key insight is that (row + col) % 2 determines the pattern: when the sum is even, use one value; when odd, use the other. This creates the alternating pattern regardless of array dimensions. The AP exam may present a filled checkerboard and ask which expression generated it, or ask you to fill a 2D array according to a position-dependent rule. The modulo approach generalizes to any repeating pattern.

Consider the following code segment.

int[][] board = new int[4][4]; for (int r = 0; r < board.length; r++) for (int c = 0; c < board[r].length; c++) if ((r + c) % 2 == 0) board[r][c] = 1; System.out.println(board[1][2] + " " + board[2][2]);

What is printed?

Answer: (B) 0 1

board[1][2]: (1+2)%2=1, not set. board[2][2]: (2+2)%2=0, set to 1. Output: 0 1.

Why Not the Others?

(A) board[1][2] has odd sum, stays 0.

(C) Reversed.

(D) board[2][2] has even sum, set to 1.

Common Mistake

Checkerboard: (r+c) % 2 alternates between 0 and 1 in a grid pattern.

AP Exam Tip

(r+c) % 2 == 0 creates a checkerboard. Even sum = 1, odd sum = 0 (default).

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.