You can print an inverted triangle by reducing the number of stars on each successive row. Use a descending outer for loop to control the row length and an inner loop to print the stars.
Source code
Save this example as InvertedTrianglePatternExample.java.
public class InvertedTrianglePatternExample {
public static void main(String[] args) {
int height = 5;
for (int row = height; row >= 1; row--) {
for (int column = 1; column <= row; column++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Explanation
The variable height sets the number of rows and the number of stars on the first row. With height = 5, the outer loop visits the values 5, 4, 3, 2, and 1.
The outer loop has three parts:
| Part | Purpose |
|---|---|
int row = height |
Start with the longest row. |
row >= 1 |
Continue while at least one star remains. |
row-- |
Subtract one after completing each row. |
The inner loop starts at column = 1 and continues while column <= row. It therefore prints exactly row stars. When the outer loop decreases row, the next execution of the inner loop prints one fewer star.
For example, when row is 5, the inner loop runs five times. When row becomes 4, the inner loop starts again at 1 and runs four times. This continues until the last row contains one star.
System.out.print("* ") prints a star followed by a space without moving to another line. After the inner loop finishes, System.out.println() ends the current row. No leading spaces are printed, so the triangle remains aligned to the left.
The descending loop uses row-- because its condition requires the counter to move toward 1. Changing it to row++ would move the counter in the wrong direction and prevent the intended five-row output.
Run the example
With a JDK installed, open a terminal in the directory containing the source file and run:
javac InvertedTrianglePatternExample.java
java InvertedTrianglePatternExample
Output
* * * * *
* * * *
* * *
* *
*
Display the output in a monospaced font to keep the pattern aligned. Trailing spaces are omitted from the output shown here.
Try it yourself
Change height to 3, then to 7. Before running each version, predict the number of rows and the total number of stars. For a positive height n, the total is n * (n + 1) / 2. The example with a height of five prints 15 stars.
Also try height = 1, which prints a single star. A zero or negative height produces no output because the outer loop condition is false at the start.
To turn the pattern upright, replace the outer loop with for (int row = 1; row <= height; row++) and leave the inner loop unchanged. Compare the result with How do I print a right triangle pattern using loops in Java?.
