Beginner Logical Thinking Java

Star Pattern Programs in Java

Print common star patterns of size n using nested for loops.

  • TimeO(n^2)
  • SpaceO(1)
  • Hints3
  • Read4 min
Quick answer

Star pattern programs in Java use an outer loop for rows and inner loops for spaces and stars. For row i of n, a right triangle prints i stars, a left triangle prints n - i spaces then i stars, and a pyramid prints n - i spaces then 2i - 1 stars. End each row with println().

Nested loopsSpaces and starsBoundary conditions
1

Problem statement

Star pattern programs in Java print shapes made of *. Given a size n, print the requested shape using loops.

The method is the same each time: count the spaces and the stars in row i. Then write one loop for each count. For number and letter shapes, see pattern programs in Java.

Input

An integer n, the number of rows.

Output

The star pattern, one row per line.

Examples

Example 1
Inputn = 3, right triangle
Output* / ** / ***

Row i has i stars. A slash marks a new line here.

Example 2
Inputn = 3, left triangle (dots show spaces)
Output..* / .** / ***

Row i has n - i spaces, then i stars.

Constraints

  • 1 <= n <= 50
  • Hollow shapes look right from n = 3
2

Think before you code

Reveal the questions to ask yourself first
  • In row i, how many spaces come before the first star?
  • How many stars are in row i?
  • For a hollow shape, which cells are on the border?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Write the space count and star count for rows 1, 2 and 3 before any code.
2 Hint 2
Pyramid rows have 1, 3, 5 stars, which is 2i - 1.
3 Hint 3
For hollow or X shapes, loop over every cell and use an if to pick star or space.
4

Approach

Reveal the step-by-step approach

The formulas

Pattern Spaces in row i Stars in row i
Right triangle 0 i
Inverted right triangle 0 n - i + 1
Left triangle n - i i
Pyramid n - i 2i - 1
Inverted pyramid i - 1 2(n - i) + 1
Butterfly, top half 2(n - i), in the middle i on each side

Two styles solve almost all of them:

  1. Count style: one loop prints spaces, the next prints stars.
  2. Grid style: visit each cell (i, j) and print a star only if a condition is true.

An understanding of loops in Java is all you need.

5

Dry run

Walk through the example step by step

Pyramid, n = 4:

i | spaces = 4 - i | stars = 2i - 1 | row (dots show spaces)
--+----------------+----------------+-----------------------
1 | 3              | 1              | ...*
2 | 2              | 3              | ..***
3 | 1              | 5              | .*****
4 | 0              | 7              | *******
6

Solution

Reveal the full Java solution
Solution.java
public class StarPatterns {
    static void print(char c, int count) {
        for (int k = 1; k <= count; k++) {
            System.out.print(c);
        }
    }

    // Prints one row: leading spaces, then stars.
    static void row(int spaces, int stars) {
        print(' ', spaces);
        print('*', stars);
        System.out.println();
    }

    public static void main(String[] args) {
        int n = 4;
        System.out.println("Right triangle");
        for (int i = 1; i <= n; i++) {
            row(0, i);
        }
        System.out.println("Inverted right triangle");
        for (int i = 1; i <= n; i++) {
            row(0, n - i + 1);
        }
        System.out.println("Left triangle");
        for (int i = 1; i <= n; i++) {
            row(n - i, i);
        }
        System.out.println("Pyramid");
        for (int i = 1; i <= n; i++) {
            row(n - i, 2 * i - 1);
        }
        System.out.println("Inverted pyramid");
        for (int i = 1; i <= n; i++) {
            row(i - 1, 2 * (n - i) + 1);
        }
    }
}

Output:

Right triangle
*
**
***
****
Inverted right triangle
****
***
**
*
Left triangle
   *
  **
 ***
****
Pyramid
   *
  ***
 *****
*******
Inverted pyramid
*******
 *****
  ***
   *

All five shapes share one row method. Only the two counts change.

Left star pattern program in Java

Here is the same left triangle with plain loops. This is a star pattern program in Java using for loop only, with no helper method.

public class LeftStar {
    public static void main(String[] args) {
        int n = 4;
        for (int i = 1; i <= n; i++) {
            for (int s = 1; s <= n - i; s++) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
   *
  **
 ***
****

Star pattern code in Java: hollow square, X, hourglass and butterfly

public class MoreStars {
    static void print(char c, int count) {
        for (int k = 1; k <= count; k++) {
            System.out.print(c);
        }
    }

    static void hollowSquare(int n) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                boolean border = i == 1 || i == n || j == 1 || j == n;
                System.out.print(border ? "* " : "  ");
            }
            System.out.println();
        }
    }

    static void xShape(int n) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                boolean onLine = i == j || i + j == n + 1;
                System.out.print(onLine ? "* " : "  ");
            }
            System.out.println();
        }
    }

    static void hourglass(int n) {
        for (int i = 1; i <= n; i++) {
            print(' ', i - 1);
            print('*', 2 * (n - i) + 1);
            System.out.println();
        }
        for (int i = 2; i <= n; i++) {
            print(' ', n - i);
            print('*', 2 * i - 1);
            System.out.println();
        }
    }

    static void butterflyRow(int i, int n) {
        print('*', i);
        print(' ', 2 * (n - i));
        print('*', i);
        System.out.println();
    }

    static void butterfly(int n) {
        for (int i = 1; i <= n; i++) {
            butterflyRow(i, n);
        }
        for (int i = n - 1; i >= 1; i--) {
            butterflyRow(i, n);
        }
    }

    public static void main(String[] args) {
        System.out.println("Hollow square");
        hollowSquare(5);
        System.out.println("X shape");
        xShape(5);
        System.out.println("Hourglass");
        hourglass(3);
        System.out.println("Butterfly");
        butterfly(3);
    }
}
Hollow square
* * * * *
*       *
*       *
*       *
* * * * *
X shape
*       *
  *   *
    *
  *   *
*       *
Hourglass
*****
 ***
  *
 ***
*****
Butterfly
*    *
**  **
******
**  **
*    *

Star pattern program in Java with explanation

  • Hollow square: a cell is on the border if it is in the first or last row or column.
  • X shape: i == j is one diagonal. i + j == n + 1 is the other.
  • Hourglass: an inverted pyramid, then a pyramid. The second part starts at row 2 so that the middle star is not printed twice.
  • Butterfly: stars, a middle gap, stars. The lower half repeats the upper rows in reverse.

A pyramid followed by its inverted form, with the widest row printed once, gives a diamond. It has its own page: diamond pattern in Java. Next, try the Java coding questions or look at the Java full stack course.

TimeO(n^2)
SpaceO(1)
7

Review before the interview

Common mistakes

  • Printing spaces after the stars in a left triangle. They must come first.
  • Using i stars in a pyramid instead of 2i - 1.
  • Printing the middle row of an hourglass or butterfly twice.
  • Mixing a star of width 1 with a gap of width 2, which bends the shape.

Edge cases to test

  • n = 1 prints one star for triangles and pyramids.
  • n = 0 prints nothing.
  • Hollow square with n = 2 is a full square, as there is no inside.
  • X shape with an even n has no single centre star.

Interview follow-ups

  • Can you build each row with String.repeat in Java 11 or later?
  • How would you make the pyramid hollow?
  • How would you print the X shape using only one loop for rows?

Keep practising

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us