9.1.7 Checkerboard V2 Codehs Here
Introduction If you are currently working through the CodeHS Java (or JavaScript) curriculum , particularly the unit on Nested Loops or 2D Arrays , you have likely encountered the infamous exercise: 9.1.7 Checkerboard V2 .
square.setColor(square.getFillColor()); Sometimes students write a complex condition like ((row % 2 == 0 && col % 2 == 0) || (row % 2 != 0 && col % 2 != 0)) . This is logically correct but verbose and error-prone. Stick with (row + col) % 2 . Advanced Variations of 9.1.7 Checkerboard V2 Variation A: Diamond or Hexagonal Checkerboard Some "V2" extensions require non-square patterns. The parity rule still applies, but you might need to offset odd rows. Example: staggered rows like a brick wall.
System.out.print("Enter number of rows: "); int rows = input.nextInt(); System.out.print("Enter number of columns: "); int cols = input.nextInt(); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) if ((i + j) % 2 == 0) System.out.print("@"); else System.out.print("."); System.out.println(); // new line after each row 9.1.7 Checkerboard V2 Codehs
If row % 2 == 1 , start with the opposite color. Equivalent to:
private static final int NUM_ROWS = 8; private static final int NUM_COLS = 8; Introduction If you are currently working through the
public void run() double sqWidth = (double) getWidth() / NUM_COLS; double sqHeight = (double) getHeight() / NUM_ROWS; for (int row = 0; row < NUM_ROWS; row++) for (int col = 0; col < NUM_COLS; col++) double x = col * sqWidth; double y = row * sqHeight; GRect square = new GRect(x, y, sqWidth, sqHeight); square.setFilled(true); if ((row + col) % 2 == 0) square.setFillColor(Color.BLACK); else square.setFillColor(Color.RED); add(square);
Whether you are printing text to the console or drawing colored rectangles on a canvas, the logic remains identical. Write your code to be flexible (no magic numbers), test edge cases (1 row or 1 column), and always double-check your starting color. Stick with (row + col) % 2
if (row % 2 == 0) // normal parity else // shifted: (col % 2 == 0) gives opposite