How to print square pattern in java.

The printing of square pattern is not so complicate we only have to print two line horizontally and two lines vertically with the required space between them.

Code for printing square pattern in java:-

import java.util.Scanner;

public class squarepattern {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n;
n = s.nextInt();
for (int i = 1; i <= n; i++) {                                                             
for (int j = 1; j <= n; j++) {
if ((j == 1) || (j == n)) {                                                     // it print  two lines horizontally when  j=1 and when j=n.  
     System.out.print(“* “);

} else if ((i == 1) || (i == n)) {                                         // it print  two lines vertically  when  i=1 and when i=n.  
           System.out.print(“* “);
} else {
             System.out.print(” “);
  }

       }
      System.out.println();
     }

  }

 }

Leave a Reply