Concentric Square of Stars

This program prints concentric squares of stars.

Problem Statement

Write a Java program that prints concentric squares of stars in a 7x7 grid.

Source Code

1 public class ConcentricSquares {
2 public static void main(String[] args) {
3 int n = 7;
4 for(int i=0; i<n; i++) {
5 for(int j=0; j<n; j++) {
6 if(i==0 || j==0 || i==n-1 || j==n-1 || i==1 || j==1 || i==n-2 || j==n-2) {
7 System.out.print("* ");
8 } else {
9 System.out.print(" ");
10 }
11 }
12 System.out.println();
13 }
14 }
15 }

Program Output

* * * * * * * 
* *       * * 
*           * 
*           * 
*           * 
* *       * * 
* * * * * * * 

Explanation

The condition checks both the outer border and a second inner border, printing stars at both layers and spaces elsewhere, so the pattern forms two nested square outlines creating a concentric effect.

Quick Links to Explore