Mastering Java Pattern Programs: Star Pyramids and Triangles Explained


Pattern printing programs are a staple in university computer science exams and junior software engineering interviews. While they might seem like a simple visual trick, pattern programs are actually an excellent way to test a developer's understanding of nested loops and coordinate logic.

If you can master pattern printing, you will have a much easier time understanding how to traverse 2D arrays and matrices later in your career.

Below, we break down how to print the most common star (*) patterns in Java. You can easily swap the star for a number or character depending on your requirements.

1. The Pyramid Star Pattern

The Logic: To print a centered pyramid, we need one outer loop and two inner loops.

  • The Outer Loop: Controls the number of rows.

  • The first inner loop prints decreasing spaces before the stars to center them.

  • The Second Inner Loop: Prints the stars with a space after each one.

The Code:

public class Main {
    public static void main(String[] args) {
        int rows = 5; // You can change this to make a larger pyramid
        // Outer loop handles the number of rows
        for (int i = 0; i < rows; i++) {
            // Inner loop 1: Handles the spaces
            for (int j = rows - i; j > 1; j--) {
                System.out.print(" ");
            }
            // Inner loop 2: Handles the stars and the spaces between them
            for (int j = 0; j <= i; j++ ) {
                System.out.print("* ");
            }
            // Moves the cursor to the next line after each row
            System.out.println(); 
        }
    }
}
The Output:
    * 
   * * 
  * * * 
 * * * * 
* * * * *

2. The Right Triangle Star Pattern (Left-Aligned)

The Logic: This is the foundational pattern. It is simpler than the pyramid because it doesn't require us to calculate leading spaces. We only need the outer loop for the rows and a single inner loop that prints the same number of stars as the current row number.

The Code:

public class Main {

    public static void main(String[] args) {

        int rows = 5;

        for (int i = 1; i <= rows; i++) {

            for (int j = 1; j <= i; j++) {

                System.out.print("* ");

            }

            System.out.println();

        }

    }

}

The Output:
* 
* * 
* * * 
* * * * 
* * * * *

When you write nested for loops like the ones above, your code runs in O(n^2) time complexity (Quadratic Time). Because for every row (n), the inner loop iterates multiple times. While O(n^2) is perfectly fine for a 5-row console pattern, it is important to recognize this complexity pattern when building larger, performance-heavy applications.


Good Luck! 😊