Java Program to Print a Right-Aligned Triangle with Spaced Stars

java program to print pattern
java program to print pattern

Program :

Write a program to print following pattern .

P7 1
Simple Star pattern

Code :

Below java program will print above pattern.

public class Pattern {
	public static void main(String[] args) {
		for (int i = 0; i <5; i++) {
			for (int j = 0; j < 5; j++) {
				if(i+j >=4)//i+j==4 || j-i==4 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 5 times (one per column). At each position the program tests i + j >= 4. When it is true, it prints a star followed by a space; otherwise it prints a single space. After each row, System.out.println() moves to the next line.

Stars per row: 1, 2, 3, 4, 5 (15 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. Reading them left to right gives the third line of the output.

Alignment note: each star is printed as a star plus a space (two characters), but each blank is only one space. That is why the rows do not line up perfectly. To align them, print two spaces for each blank.

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