66.2k views
5 votes
Java

Write a program Checkerboard that takes an integer command-line argu-
ment n and uses a loop nested within a loop to print out a two-dimensional n-by-n
checkerboard pattern with alternating spaces and asterisks.

User PierreN
by
8.6k points

1 Answer

1 vote
public class Checkerboard {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((i + j) % 2 == 0) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

The program takes an integer command-line argument n and uses two nested loops to print out an n-by-n checkerboard pattern. The if statement inside the inner loop checks if the sum of the current row index i and column index j is even, and if so, it prints an asterisk. Otherwise, it prints a space.
User Tozka
by
8.2k points