Checkerboard Pattern

easy Pattern Printing

Problem

Read n and print an n by n checkerboard. Print # when row + column is even and print . when it is odd. The top-left cell is #. Use 0-based row and column numbers.

Constraints

  • 1 <= n <= 30

Examples

Input

3

Output

#.#
.#.
#.#

Solutions

Best approachTime O(n^2)Space O(1)

Moving one step right or down changes row + column from even to odd or from odd to even, so the symbols alternate in both directions.

Same code works in Java810172125Basic features only, so nothing changes between versions.

Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).

/*
 * Problem : Checkerboard.
 * Input   : One integer n (side length).
 * Output  : n lines of # and .
 * Approach: Alternate the two symbols.
 * Time    : O(n^2)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int size = new Scanner(System.in).nextInt();

        // Step 1: Repeat once for each row. Row numbers start at 0.
        for (int row = 0; row < size; row++) {
            StringBuilder line = new StringBuilder();

            // Step 2: Visit each column of the row. Column numbers start at 0.
            for (int column = 0; column < size; column++) {
                // Step 3: Same parity (even sum) gives #. Different parity (odd sum) gives a dot.
                line.append((row + column) % 2 == 0 ? "#" : ".");
            }

            // Step 4: Print the finished line.
            System.out.println(line);
        }
    }
}
Hints (1)
  1. What happens to row + column when you move one cell to the right?