Java Program to Print an Inverted Right Triangle Star Pattern

Patterns (1)

Write a Program to print following pattern !

pattrens with java
pattrens with java

Solution :

Here is the Java code print the 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)
				{
					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; otherwise it prints nothing. After each row, System.out.println() moves to the next line.

Stars per row: 5, 4, 3, 2, 1 (15 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