Java Practice Program: diamond shape pattern

Write a Java program that prints a diamond shape pattern.

This Java program prints a diamond shape pattern of stars (*). It consists of two main parts:

  1. The first loop prints the top half of the diamond (an upright pyramid).
  2. The second loop prints the bottom half of the diamond (an inverted pyramid).
class Main {
    public static void main(String[] args) {
       int rows=10;
        for(int i=1;i<=rows;i++){
            for(int j=i;j<=rows;j++){
                System.out.print(" ");
            }
            for(int k=1;k<=(2*i-1);k++){
                System.out.print("* ");
            }
            System.out.println();
        }
        for(int i=rows-1;i>=1;i--){
            for(int j=rows;j>i;j--){
                System.out.print(" ");
            }
            for(int k=1;k<=(2*i-1);k++){
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output:

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

Code Breakdown
int rows = 10;

This sets the number of rows for the diamond pattern. The number of rows in the upper half is 10, and the lower half has 9 rows.

Top Half of the Diamond:
The first for loop (for (int i = 1; i <= rows; i++)) handles the top half of the diamond, which is an upright pyramid.
Spaces: The first inner for loop (for (int j = i; j <= rows; j++)) prints the spaces before the stars.
Stars: The second inner for loop (for (int k = 1; k <= (2 * i – 1); k++)) prints the stars. The number of stars increases by 2 with each row.

Bottom Half of the Diamond:
The second for loop (for (int i = rows – 1; i >= 1; i–)) handles the bottom half of the diamond, which is an inverted pyramid.
Spaces: The first inner for loop (for (int j = rows; j > i; j–)) prints the spaces before the stars.
Stars: The second inner for loop (for (int k = 1; k <= (2 * i – 1); k++)) prints the stars. The number of stars decreases by 2 with each row.
System.out.println();

After printing each row (spaces and stars), the program moves to the next line using this statement.

Key Points


The upper half (top part) forms a pyramid, and the lower half forms an inverted pyramid.
Symmetry: The number of stars starts with 1 in the first row, increases by 2 in each subsequent row until it reaches the middle, and then decreases by 2 in each row after that.
Adjustable Size: You can change the rows variable to create a smaller or larger diamond. The pattern’s width and height will be proportional to the value of rows.

Leave a Reply