Java ProgramsPatternsPrint Right Triangle

Print Right Triangle in Java

beginner·  Patterns  ·  Star Patterns

Problem

A right triangle pattern gets its name from the 90-degree corner it forms — a left-aligned block where each row has exactly one more star than the row before it.

Given a size n, print a left-aligned triangle of stars where row i has i stars.

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

Java Program

Java
public class RightTriangle { public static void main(String[] args) { int n = 5; for (int i = 1; i <= n; i++) { 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

Tying the inner loop's stop condition to the outer loop's own counter makes each row exactly one star longer than the row before it, star by star.

How It Works
  1. 1The outer for (int i = 1; i <= n; i++) runs once per row.
  2. 2The inner for (int j = 1; j <= i; j++) stops at i itself — row 1 prints one star, row 2 prints two, and so on.
  3. 3A separating space is added before every star except the first in a row, so no line ends with a trailing space.
  4. 4Each row is printed as soon as its inner loop finishes.
For n = 5, row 3's inner loop runs j = 1 to 3, printing exactly three stars.
💡

Key Point: The inner loop bound j <= i, not a fixed number, is the entire difference between this triangle and a solid square of the same width.

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

Why: The total stars printed across all rows is 1 + 2 + ... + n, which is O(n²), with no growing storage.

Key Concepts

nested for loopvariable inner boundStringBuilder

Related Programs