Print Left-Aligned Triangle in Java
Problem
The same growing 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 i stars, building each row without a nested loop.
Java Program
public class LeftAlignedTriangle {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
System.out.println("* ".repeat(i).trim()); // builds the whole row as one string, no inner loop
}
}
}Output
Core Logic
String's own repeat() method can generate an entire row's worth of stars in one call, replacing a second counting loop with a single string operation per row.
- 1A single
for (int i = 1; i <= n; i++)loop selects the row — 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. - 4The finished row string is printed directly, with no accumulation needed.
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²).