Java ProgramsPatternsPrint Inverted Triangle

Print Inverted Triangle in Java

beginner·  Patterns  ·  Star Patterns

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.

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

Java Program

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

How It Works
  1. 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. 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. 4As i counts down, each successive row's string is shorter than the last.
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 loopdecrementing counter

Related Programs