Java Program to Print a Sideways Hourglass Star Pattern

Star Patterns
Star Patterns

Problem :

Write a program to solve given pattern .

Program to print given star pattern in Java using simple Trick !
Pattern in Java

Solution :

Here is the code to solve the given pattern .

public class Pattern {
	public static void main(String[] args) {
		for (int i = 0; i <9; i++) {
			for (int j = 0; j < 5; j++) {
				if(  j-i<=-4 || i+j<=4) //
				{
					System.out.print("*");
				}
				else
				{
					System.out.print(" ");
				}
			}
			System.out.println();
		}
	}
}

Expected output

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

How the logic works

The outer loop i runs 9 times (one per row) and the inner loop j runs 5 times (one per column). At each position the program tests j - i <= -4 || i + j <= 4. When it is true, it prints a star; otherwise it prints a single space. After each row, System.out.println() moves to the next line.

Stars per row: 5, 4, 3, 2, 1, 2, 3, 4, 5 (29 in total).

Quick dry run

Take the third row, where i = 2. The condition gives these results: j=0: star, j=1: star, j=2: star, j=3: blank, j=4: blank. Reading them left to right gives the third line of the output.

FAQ

Why do these programs use i + j and j – i?
In a grid, every cell on the same anti-diagonal has the same i + j value, and every cell on the same diagonal has the same j - i value. Comparing them with a number draws the straight edges of the shape.

Can I use the same logic in C++ or Python?
Yes. Only the loop and print syntax change. The condition on i and j stays the same.

More star patterns: Star patterns set 1, Star patterns set 2, Star patterns set 3, Star patterns set 4, Star pattern set 5.

Leave a Reply