Prime Checkerboard Grid

This program prints a checkerboard of prime and non-prime indicators.

Problem Statement

Write a Java program that prints a 4x4 checkerboard grid where prime numbers are marked as 1 and non-primes as 0.

Source Code

1 public class PrimeCheckerboard {
2 public static void main(String[] args) {
3 int num = 2;
4 for(int i=0; i<4; i++) {
5 for(int j=0; j<4; j++) {
6 boolean prime = true;
7 for(int k=2; k<=num/2; k++) {
8 if(num % k == 0) {
9 prime = false;
10 break;
11 }
12 }
13 System.out.print((prime ? "1 " : "0 "));
14 num++;
15 }
16 System.out.println();
17 }
18 }
19 }

Program Output

1 1 1 0 
1 0 1 0 
1 0 0 1 
0 1 0 0 

Explanation

Each number is checked for primality. If prime, print 1; else 0. Nested loops arrange results in checkerboard form. Shows how nested loops can generate prime checkerboards.

Quick Links to Explore