Java Program to Print an Inverted Pyramid Star Pattern

pattern 10
pattern 10

Program :

Write a program to print following pattern.

P10
Pattern 10

Solution :

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

Expected output

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

How the logic works

The outer loop i runs 5 times (one per row) and the inner loop j runs 9 times (one per column). At each position the program tests j - i >= 0 && i + j <= 8. 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: 9, 7, 5, 3, 1 (25 in total).

Quick dry run

Take the third row, where i = 2. The condition gives these results: j=0: blank, j=1: blank, j=2: star, j=3: star, j=4: star, j=5: star, j=6: star, j=7: blank, j=8: 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