How to print Hollow Square Pattern in Java - Step by Step Examples
How to print Hollow Square Pattern in Java ?
Answer
To print a Hollow Square Pattern in Java, we use nested loops. The outer loop controls the rows, and the inner loops control the columns and the conditions for printing the hollow square pattern.
✐ Examples
1 Hollow Square Pattern
In this example,
- We define a function
printHollowSquare
that takes the size of the squaren
as a parameter. - We use two nested
for
loops to iterate over rows and columns. - Within the loops, we check if we are at the first or last row or column, or if the current position is on the border of the square. If so, we print a star (*); otherwise, we print a space.
Java Program
// Hollow Square Pattern
public class Main {
public static void printHollowSquare(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || i == n - 1 || j == 0 || j == n - 1)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
public static void main(String[] args) {
printHollowSquare(5);
}
}
Output
***** * * * * * * *****
Summary
In this tutorial, we learned How to print Hollow Square Pattern in Java language with well detailed examples.
More Java Pattern Printing Tutorials
- How to print Left Half Pyramid Pattern in Java ?
- How to print Right Half Pyramid Pattern in Java ?
- How to print Pyramid Pattern in Java ?
- How to print Rhombus Pattern in Java ?
- How to print Diamond Pattern in Java ?
- How to print Hour Glass Pattern in Java ?
- How to print Hollow Square Pattern in Java ?
- How to print Hollow Pyramid Pattern in Java ?
- How to print Hollow Inverted Pyramid Pattern in Java ?
- How to print Hollow Diamond Pattern in Java ?
- How to print Floyd's Trianlge Pattern in Java ?
- How to print Pascal's Triangle Pattern in Java ?