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

You can print a right triangle by increasing the number of stars on each row. Unlike a rectangle, the inner loop limit depends on the current row number.

Source code

Save this example as RightTrianglePatternExample.java.

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

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

Explanation

The outer loop counts from 1 through height, including the last row. The inner loop counts from 1 through row. As a result, row 1 contains one star, row 2 contains two stars, and row 5 contains five stars.

The condition column <= row creates the sloping edge. If you replace row with height in that condition, every row contains the same number of stars and the output becomes a square pattern.

For a positive height n, the total number of stars is 1 + 2 + ... + n, which equals n * (n + 1) / 2. This example prints 15 stars.

Run the example

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

javac RightTrianglePatternExample.java
java RightTrianglePatternExample

Output

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

Display the output in a monospaced font to keep the pattern aligned. Trailing spaces are omitted from the output shown here.

Try it yourself

Print an inverted triangle by changing the outer loop to for (int row = height; row >= 1; row--). Keep the inner loop unchanged.

Leave a Reply

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