How do I print a right-aligned triangle pattern using loops in Java?

You can print a right-aligned triangle by placing spaces before the stars on each row. As the number of stars increases, reduce the number of empty positions so the right edge stays aligned.

Source code

Save this example as RightAlignedTrianglePatternExample.java.

public class RightAlignedTrianglePatternExample {
    public static void main(String[] args) {
        int height = 5;

        for (int row = 1; row <= height; row++) {
            for (int space = 0; space < height - row; space++) {
                System.out.print("  ");
            }
            for (int star = 0; star < row; star++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Explanation

The outer loop counts from 1 through height. Its counter, row, determines how many stars to print on the current line.

Inside the outer loop, two loops run in sequence. The first prints height - row empty positions. The second prints row stars. These counts always add up to height, so every row occupies the same number of logical positions.

For a height of five, the counts are:

Row Empty positions Stars
1 4 1
2 3 2
3 2 3
4 1 4
5 0 5

Each empty position uses two spaces, " ". Each star position uses a star followed by a space, "* ". Both occupy two character positions, keeping the rightmost star in the same column on every row. Printing only one space per empty position would break this alignment.

On the first row, the program prints eight leading spaces followed by one star and its trailing space. On the last row, the leading-space loop does not execute because height - row is zero, and the star loop prints five stars.

System.out.print() writes each part on the current line. System.out.println() runs after both inner loops to start the next row.

Run the example

With a JDK installed, open a terminal in the directory containing the source file and run:

javac RightAlignedTrianglePatternExample.java
java RightAlignedTrianglePatternExample

Output

        *
      * *
    * * *
  * * * *
* * * * *

Display the output in a monospaced font to preserve alignment. Trailing spaces are omitted from the output shown here; leading spaces are preserved.

Try it yourself

Change height to 3, then to 7. For each row, calculate the number of empty positions and stars before running the program. A positive height n produces n rows and n * (n + 1) / 2 stars.

Try height = 1, which prints a single star without leading spaces. A zero or negative height produces no output because the outer loop never executes.

Finally, remove the first inner loop and compare the result with How do I print a right triangle pattern using loops in Java?. The number of stars stays the same, but the triangle becomes left-aligned.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.