Java Program To Print Hollow Square
Java Loops JAVA Programming Language

Java Program To Print Hollow Square

We are back with another example of the loops in java. In this article, we are going to teach you how to write a Java Program To Print Hollow Square using for loop. So, let’s create the program.

Java Program To Print Hollow Square:

Simply take the values of rows and columns from the user. Next, we all know that pattern is printed with the help of a nested loop (loop within a loop). In this program, the outer loop will iterate from 1 to the number of rows and the inner loop will iterate from 1 to the columns. And now we have to use the if statement.

In the if statement the condition is if ‘i’ is equal to 1 or ‘i’ is equal to rows or j is equal to or j is equal to the number of columns. If any condition will meet then print the star else print the space. So, this is the whole logic of how to print hollow square in java.

Code Of Java Program To Print Hollow Square:

import java.util.*;
public class HollowSquare {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter The Number Of Rows : ");
        int rows = sc.nextInt();
        System.out.print("Enter The Number Of Columns : ");
        int cols = sc.nextInt();


        for(int i =1; i<=rows; i++){
            for(int j=1; j<=cols; j++){
                if(i ==1 || j==1 || i== rows || j==cols){
                    System.out.print("*");
                }
                else{
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}

 

Output:

Java Program To Print Hollow Square
Java Program To Print Hollow Square

 

 

 

 

 

From the above program, we conclude how to write a Java Program to print the hollow square. If you are searching for more advanced patterns in java then you are right place please click on the link to check the best advanced patterns in java.

Leave a Reply

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