Print Inverted Triangle in Java
Problem
The same shrinking triangle shape can be produced by building each row's content as a single string operation, instead of printing one star at a time inside a second loop.
Given a size n, print a left-aligned triangle of stars where row i has n minus i plus one stars, building each row without a nested loop.
Java Program
public class InvertedTriangle {
public static void main(String[] args) {
int n = 5;
for (int i = n; i >= 1; i--) {
System.out.println("* ".repeat(i).trim()); // builds the whole row as one string, no inner loop
}
}
}Output
Core Logic
Counting the row loop down from n to 1, and handing each row's star count straight to String's repeat() method, shrinks the row in one string operation instead of a second counting loop.
- 1A single
for (int i = n; i >= 1; i--)loop selects the row and its star count together — there's no second loop nested inside it. - 2
"* ".repeat(i)repeats the two-character unit"* "exactlyitimes, producingistars each followed by a space. - 3
.trim()removes the one trailing space that repetition leaves at the end of the row. - 4As
icounts down, each successive row's string is shorter than the last.
i = 3, "* ".repeat(3) gives "* * * ", and .trim() reduces it to "* * *".Key Point: This builds each row in one step instead of counting stars one at a time — a genuinely different technique from a classic nested loop, even though the printed shape comes out identical.
Why: repeat() still does O(i) work internally to build each row's string, so the total across all n rows remains O(n²).