Java Practice Program: diamond-shaped pattern

Write a Java program that prints a diamond-shaped pattern.

This program prints a diamond-shaped pattern of stars (*). The diamond is composed of two parts: a top half (pyramid) and a bottom half (inverted pyramid).

class Main {
    public static void main(String[] args) {
        final int ROW_COUNT = 5;  // Size of the diamond (height of the top half)

        // Top half of the diamond (pyramid)
        for (int row = ROW_COUNT; row >= 1; row--) {
            // Print spaces before the stars
            for (int space = ROW_COUNT; space > row; space--) {
                System.out.print(" ");
            }
            // Print stars
            for (int star = 1; star <= (2 * row - 1); star++) {
                System.out.print("*");
            }
            // Move to the next line
            System.out.println();
        }

        // Bottom half of the diamond (inverted pyramid)
        for (int row = 2; row <= ROW_COUNT; row++) {
            // Print spaces before the stars
            for (int space = ROW_COUNT; space >= row; space--) {
                System.out.print(" ");
            }
            // Print stars
            for (int star = 1; star <= (2 * row - 1); star++) {
                System.out.print("*");
            }
            // Move to the next line
            System.out.println();
        }
    }
}

Output:

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

Top Half (Pyramid)
Outer Loop (for (int row = ROW_COUNT; row >= 1; row–))

Starts from the largest row (ROW_COUNT) and decreases to 1.
Each iteration builds one row of the top half.
Spaces (for (int space = ROW_COUNT; space > row; space–))

Prints spaces to align stars to the center.
Stars (for (int star = 1; star <= (2 * row – 1); star++))

Prints an odd number of stars in each row (1, 3, 5, …).
The number of stars decreases with each row.

  1. Bottom Half (Inverted Pyramid)
    Outer Loop (for (int row = 2; row <= ROW_COUNT; row++))

Starts from 2 and goes up to ROW_COUNT.
Each iteration builds one row of the bottom half.
Spaces (for (int space = ROW_COUNT; space >= row; space–))

Prints spaces to align stars to the center.
Stars (for (int star = 1; star <= (2 * row – 1); star++))

Prints an odd number of stars in each row (3, 5, 7, …).
The number of stars increases with each row.


Key Points
The top half forms an inverted pyramid (decreasing rows of stars).
The bottom half forms a pyramid (increasing rows of stars).
The combination creates a symmetric diamond pattern.

Leave a Reply