Java Program to Print a Pyramid Star Pattern

Patterns in java

Program :

Write a program to solve given pattern .


Patterns for Interview preparation , using simple trick !
Patterns for Interview preparation , using simple trick !

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(i+j>=4 && j-i<=4)
				{
					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 i + j >= 4 && j - i <= 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: 1, 3, 5, 7, 9 (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