Print Pyramid Star Pattern in Java

Topic

In this program, we are required to print a pyramid-shaped pattern using stars (*) in Java. A pyramid pattern is one where each row has an increasing number of stars centered horizontally, forming a triangle. This is a classic pattern printing program asked in Java interviews to test understanding of loops and logic building.

Examples

Input: 4

Output:
   *
  ***
 *****
*******
Input: 1

Output:
*
Input: 0

Output:
(no output)

Explanation:

  • Each row contains increasing odd numbers of stars: 1, 3, 5, ...
  • Spaces are used on the left side to align the stars in a centered pyramid.

Interviewer Expectations

The interviewer wants to assess your understanding of:

  • Nested loops (outer loop for rows, inner loops for spaces and stars)
  • Loop conditions and counters
  • Control flow and formatting console output

Approach

We need to print N rows. For each row:

  1. Print (N - row) spaces to shift stars to the right.
  2. Print (2 * row - 1) stars to form the pyramid structure.
This means for row 1: 3 spaces + 1 star, row 2: 2 spaces + 3 stars, etc.

Dry Run (N = 4)

Row 1: spaces = 3, stars = 1 → "   *"
Row 2: spaces = 2, stars = 3 → "  ***"
Row 3: spaces = 1, stars = 5 → " *****"
Row 4: spaces = 0, stars = 7 → "*******"

Java Program

public class PyramidPattern {
  public static void main(String[] args) {
    int rows = 4;

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

      // print stars
      for (int k = 1; k <= 2 * i - 1; k++) {
        System.out.print("*");
      }

      // move to next line
      System.out.println();
    }
  }
}
   *
  ***
 *****
*******

Possible Followup Questions with Answers

1. How to make the pyramid pattern upside down?

You can reverse the loop — start from the max row down to 1 and adjust space and star counts accordingly.

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

2. How to print a half pyramid (right-angled triangle)?

Remove space printing, and print stars only for the current row:

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

3. How to take input from the user instead of hardcoding?

Scanner sc = new Scanner(System.in);
int rows = sc.nextInt();

Then use the same loop structure with the user-defined value.

Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗