Unit 4 Cycle 2 Day 25: 2D Array: Checkerboard Pattern
Share
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.
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).