Print Inverted Right Triangle in Java
beginner· Patterns · Star Patterns
Problem
Flipping a growing triangle upside down just means counting the star count downward instead of upward — row 1 starts at the full width, and every later row has one fewer star.
Given a size n, print a left-aligned triangle of stars where row i has n minus i plus one stars.
Input
n = 5
Output
* * * * *
* * * *
* * *
* *
*
Java Program
Java
public class InvertedRightTriangle {
public static void main(String[] args) {
int n = 5;
for (int i = n; i >= 1; i--) { // counts down, so each row has fewer stars than the last
StringBuilder row = new StringBuilder();
for (int j = 1; j <= i; j++) {
if (row.length() > 0) row.append(" ");
row.append("*");
}
System.out.println(row);
}
}
}Output
* * * * *
* * * *
* * *
* *
*
Core Logic
Starting the outer loop at n and counting it down, while the inner loop still runs from 1 up to the outer counter, shrinks each row instead of growing it.
How It Works
- 1The outer
for (int i = n; i >= 1; i--)starts at the full width and decreases by one each row. - 2The inner
for (int j = 1; j <= i; j++)still stops at the outer counter — but sinceiis now shrinking, so is every row's star count. - 3A separating space is added before every star except the first in a row, the same convention as the growing triangle.
- 4The first row printed is the widest, and the last row printed is a single star.
For
n = 5, the first row prints five stars and the last row prints exactly one.💡
Key Point: Only the outer loop's direction changes here — flipping i++ to i-- and swapping the start and stop values is the entire difference from the growing triangle.
Complexity
Time Complexity: O(n²)Space Complexity: O(1)
Why: The total stars printed across all rows is still n + (n-1) + ... + 1, which is O(n²), with no growing storage.
Key Concepts
nested for loopdecrementing outer counterStringBuilder