Jan 9, 2018 at 11:56 am Java

How to Create a Checkerboard pattern Using Asterisks in Java

Here is a simple program to draw a checkerboard pattern in Java. There can be a different way of doing it. In this case, the program pads every other row with a space to have a zigzag effect.

To do that the program checks if the row number is even and if it is, it prints spaces at the beginning of the row. It uses the modulus operator (%) and the if/else code.

The if/else section should be placed in the outer loop to limit the space to only the beginning of the row.

Checkerboard Pattern in Java

 

Here is the Java code:


/** This program prints a checkerboard pattern using the asterisk symbol (*) using
  * rows and columns sizes are given by the user
**/
import java.util.*; //Import it to use the Scanner class
public class makeCheckerboardPattern{
   public static void checkerboard(int row, int col){
       for(int i = 1; i<=row; i++){
	       if(i%2 ==0) {
		   System.out.print("  "); //Start with space on every other row
	       }
		for(int j=1; j<=col; j++) {
		    System.out.print(" * ");
		}
		System.out.println();
	}
  }

  public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.println("Please enter row size");
      int rowSize = input.nextInt();
      System.out.println("Please enter columnSize");
      int colSize = input.nextInt();
      System.out.println("Here is the checkerboard pattern\n");
      makeCheckerboardPattern(rowSize, colSize); //call the method
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *