Print Nested Square Pattern

Harish B
2 min readOct 10, 2022

In this we are going to see about “How to Print Nested Stars and Dots Square Pattern”.

Example:

If input is given as 8

After getting input from user, we will create an array to get the position of stars and dots. When array is initialized all the elements will be 0. Array is iterated in for loop to specify the position of the stars by incrementing the element to 1. For the increment if condition is created to make increment on specific position. Below if condition is used:

The idea is to run two nested loops from 1 to n for rows and columns and now to check for conditions when to print an asterisk(‘*’) and when to print dot(‘. ‘). Two variables srow(starting row), erow(ending row) is used to maintain the layers indent inside the square.

Below is the implementation java code for the above idea:

At last nested for loop is used to iterate through array and print star(“* ”) if the element is 1, else dot(“. ”).

Time Complexity: O(n3)
Auxiliary Space: O(n)

If it feels difficult, try to print separate single hollow squares with left indent.

--

--