Facebook Pixel

Printing a Diamond Star Pattern

Learn how to combine previously learned patterns to create complex composite shapes, like the classic diamond pattern.

The Art of Composite Patterns

A diamond pattern is the most famous composite star pattern. It looks incredibly complex, but if you draw a horizontal line through the middle of it, the secret is revealed.

Deconstructing the Diamond

If N = 3 (representing the top half height):

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

A diamond is nothing more than a Standard Pyramid sitting directly on top of an Inverted Pyramid.

The Implementation Strategy

You do not need a massive, convoluted loop. You just write two completely separate outer loops back-to-back.

Part 1: The Top Half

for (int row = 1; row <= n; row++) {
    for (int space = 1; space <= n - row; space++) print(" ");
    for (int star = 1; star <= 2 * row - 1; star++) print("*");
    println();
}

Part 2: The Bottom Half Since the middle row (the widest part) is already printed by the top half, the bottom half should be one row shorter (start from n - 1).

for (int row = n - 1; row >= 1; row--) {
    for (int space = 1; space <= n - row; space++) print(" ");
    for (int star = 1; star <= 2 * row - 1; star++) print("*");
    println();
}

The Takeaway

Never try to solve a complex composite pattern with a single outer loop. Break the visual shape into smaller, familiar components (triangles, squares, pyramids) and write sequential loops to build the shape piece by piece.

A composite pattern is a complex visual shape that is built by combining two or more simpler patterns, like triangles or pyramids, back-to-back.

Mentally split it in half horizontally. The top half is a standard centered pyramid. The bottom half is an inverted centered pyramid.

The top half prints the widest row. If the bottom half started at N, it would duplicate the widest row, making the center of the diamond too thick.

Yes, by iterating from 1 to 2N-1 and using absolute values or complex math to calculate spaces, but splitting it into two loops is much cleaner and easier to read.

It is O(N^2), as both the top half and bottom half take O(N^2) time. The sum is O(2N^2), which simplifies to O(N^2).

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.