Java ProgramsPatternsPrint Left-Aligned Triangle

Print Left-Aligned Triangle in Java

beginner·  Patterns  ·  Star Patterns

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.

Input
n = 5
Output
* * * * * * * * * * * * * * *

Java Program

Java
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.

How It Works
  1. 1A single for (int i = 1; i <= n; i++) loop selects the row — there's no second loop nested inside it.
  2. 2"* ".repeat(i) repeats the two-character unit "* " exactly i times, producing i stars each followed by a space.
  3. 3.trim() removes the one trailing space that repetition leaves at the end of the row.
  4. 4The finished row string is printed directly, with no accumulation needed.
For row 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.

Complexity
Time Complexity: O(n²)Space Complexity: O(1)

Why: repeat() still does O(i) work internally to build each row's string, so the total across all n rows remains O(n²).

Key Concepts

String.repeat()single loopString.trim()

Related Programs