Java star pattern
In the previous post, I have discussed some basics of pattern programs and how pattern programs work. If you are a beginner (like me) and have not seen my previous post I suggest you to please check 1 – Java program to print star pattern before continuing further.

Today I am going to show you how to draw a slightly different star pattern rectangle or square box like this:

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

So basically, if we print spaces between each column it will look like a square, otherwise, it will look like a rectangle as shown above.

About this program

This program draws a hollow rectangular or square shaped pattern using two for loops.



Code Explanation

Here the logic is same as previous program 1 – Java program to print star pattern. The only difference is that it is a hollow pattern.

From the above picture, we can see that we have to print only the row 1, row 5 and column 1, column 5 to get the desired pattern. Hence to meet this condition we have used if..else“.

Here we already know that i=row and j=column. So we can do like this:

If i is equal to 1 or i is equal to 5 or j is equal to 1 or j is equal to 5, then print “*” else print a blank space.

2 – Java program to print hollow star pattern (Rectangle / Square)
Tagged on:         

3 thoughts on “2 – Java program to print hollow star pattern (Rectangle / Square)

Leave a Reply

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