Java Right-Aligned Triangle Star Pattern

Beginner
6 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A right-aligned right-angled triangle grows by one star per row, but the right edge stays flush — you get there by printing leading spaces before the stars.

Remember
Rule: on row i, print (rows - i) spaces, then i stars

    *
   **
  ***
 ****
*****     ← 5 rows (right edge straight)

Compared with Program 1, you keep the same i star counts and add a second inner loop for (rows - i) spaces. That is the usual stepping stone toward centered pyramids.

How to Solve It

Two ways to emit the same shape — start with nested space/star loops, then optionally shorten with String.repeat.

MethodIdeaBest for
Nested loopsOuter = rows; first inner = spaces, second = starsLearning, interviews, exams
String.repeatBuild padding and star run in one call eachShorter demos once formulas click (Java 11+)

Pseudocode

Pseudocode
for i from 1 to rows:
    print (rows - i) spaces (no newline)
    print i stars (no newline)
    print newline

Cheat sheet

GoalPattern
Walk each rowfor (i = 1; i <= rows; i++)
Leading spacesfor (j = 1; j <= rows - i; j++) System.out.print(" ");
Print i starsfor (k = 1; k <= i; k++) System.out.print("*");
End the rowSystem.out.println();
Row width check(rows - i) + i == rows
One-line shortcutSystem.out.print(" ".repeat(rows - i)); System.out.println("*".repeat(i));
Invert laterGrow spaces, shrink stars → Program 4

Printing Stars vs Starting a New Line

APIEffectUse for
System.out.printStays on the same lineEach space and each *
System.out.printlnEnds the current lineAfter both inner loops

Live Preview

Change the row count and the right-aligned triangle updates instantly — including the star total.

Whole numbers from 1 to 20. Each row is exactly rows characters wide.

Live result 5 rows · 15 stars
    *
   **
  ***
 ****
*****

Worked Walkthrough — rows = 4

Trace spaces, stars, and total width for each outer-loop value of i.

iSpaces rows - iStars iWidthPrinted row
1314*
2224**
3134***
4044****

Star total: 1 + 2 + 3 + 4 = 10 = 4×5/2 — same as Program 1. Every row width is 4, which keeps the right edge flush. That is why time is O(n²).

Java Programs

Three complete programs: nested space/star loops, Scanner input, and a String.repeat shortcut. Use View Output to reveal sample results.

Example 1 — Fixed rows = 5

Hard-coded height — space loop first, then star loop.

Java
public class RightAlignedTriangle {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

How It Works

1. Set height. rows = 5 means five lines; every line is 5 characters wide.

2. Outer loop picks the row. i runs from 1 to rows.

3. Spaces, then stars. Print rows - i spaces, then i stars with System.out.print.

4. Break the line. System.out.println() after both inner loops starts the next row.

When i = 1 you get 4 spaces and 1 star; when i = 5 you get 0 spaces and 5 stars.

Example 2 — User Input Version

Read the height at runtime with Scanner. Prefer hasNextInt() in real apps (shown in the tip below).

Java
import java.util.Scanner;

public class RightAlignedTriangleInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number of rows: ");
        int rows = sc.nextInt();

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

How It Works

1. Prompt and read. Ask for a row count, then store it with sc.nextInt().

2. Same space/star core. Only the source of rows changes — the print logic matches Example 1.

3. Safer input tip. Non-numeric input throws InputMismatchException. Prefer:

Safer input
if (!sc.hasNextInt()) {
    System.out.println("Enter a positive whole number.");
    return;
}
int rows = sc.nextInt();
if (rows < 1) {
    System.out.println("Enter a positive whole number.");
    return;
}

Example 3 — "*".repeat() for Spaces and Stars

Build each row’s padding and star run in one call each — same shape, no explicit character loops (Java 11+).

Java
public class RightAlignedTriangleRepeat {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            System.out.print(" ".repeat(rows - i));
            System.out.println("*".repeat(i));
        }
    }
}

How It Works

1. Same outer loop. Still walk i from 1 to rows.

2. Build each segment. " ".repeat(rows - i) is the margin; "*".repeat(i) is the star run.

3. Print and advance. Use print for spaces and println for stars so the row ends correctly.

Learn the two-loop version first (Examples 1–2) so you can explain both bounds in an interview; treat this as a polish shortcut afterward.

Edge Cases & Pitfalls

Check these before calling the solution done.

No space loop

Left-aligned again

Skipping the space loop reprints Program 1. Print rows - i spaces before the stars.

Swapped counts

Broken right edge

Using i spaces and rows - i stars no longer flush-aligns on the right. Keep spaces = rows - i and stars = i.

Tabs

Uneven columns

Always print the space character " ", not tabs — tab width varies and skews the edge.

rows = 1

Single star

0 spaces + 1 star — same as Program 1 for n = 1. A good sanity check.

rows ≤ 0

Empty output

Outer loop never runs. Validate and re-prompt for interactive programs.

Bad input

Use hasNextInt()

nextInt() throws on letters — prefer sc.hasNextInt() and require rows >= 1.

Time and Space Complexity

ProgramTimeExtra space
Nested space/star loops (Examples 1–2)O(rows²)O(1)
String.repeat (Example 3)O(rows²)O(rows) temporary per row string

Each of n rows prints exactly n characters (spaces + stars). Star total is still n(n+1)/2 — quadratic in n.

Key Takeaways

  • Rule: print rows - i spaces, then i stars.
  • Same stars as Program 1: only the leading spaces change the picture.
  • Break the row: call println only after both inner loops.
  • Complexity: O(n²) time; O(1) extra space for nested loops.

One line: for each row i, print rows - i spaces and i stars, then println.

Frequently Asked Questions

After choosing row i, print (rows - i) space characters, then print i stars. Row 1 has rows minus 1 spaces and one star; row rows has no spaces and rows stars. Stars line up along the right edge.
Spaces and stars change with different formulas each row. One inner loop prints spaces from 1 to rows minus i, and a second prints stars from 1 to i. Without the space loop, output stays left-aligned like Program 1.
Program 1 prints only i stars per row. Program 3 prints (rows - i) spaces first, then i stars, so the same star counts appear shifted to the right.
System.out.print stays on the same line. System.out.println ends the current line. Spaces and stars use print; the row break uses println after both inner loops.
Every row prints exactly rows characters before the newline: (rows - i) spaces plus i stars.
O(n²) for n rows. Each row prints on the order of n characters (spaces plus stars), for n rows.
Yes. System.out.print(" ".repeat(rows - i)); System.out.println("*".repeat(i)); builds each row without explicit inner character loops (Java 11+).
Check sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you know?

Right-aligned and left-aligned triangles use the same star counts per row; only leading spaces change. Each row prints exactly rows characters before the newline: (rows - i) + i = rows.

Next: Inverted Right-Aligned

Grow the leading spaces and shrink the stars for an upside-down right edge.

Program 4 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful