Java Code Example: Diamond Pattern

This program prints a diamond pattern of asterisks (*). The pattern consists of two pyramids, one facing up and one facing down, with an empty line between them.

The program uses two for loops to print the upper and lower pyramids. The number of rows in the pattern is set to 8 in this example, but it can be changed by modifying the rows variable.

Code Example

public class DiamondPattern {
  public static void main(String[] args) {
    int i, j, rows = 8;

    // upper pyramid
    for (i = 0; i <= rows; i++) {
      for (j = 1; j <= rows - i; j++) {
        System.out.print(' ');
      }
      for (j = 1; j <= 2 * i - 1; j++) {
        System.out.print('*');
      }
      System.out.print("\n");
    }

    // lower pyramid
    for (i = rows - 1; i >= 1; i--) {
      for (j = 1; j <= rows - i; j++) {
        System.out.print(' ');
      }
      for (j = 1; j <= 2 * i - 1; j++) {
        System.out.print('*');
      }
      System.out.print("\n");
    }
  }
}

Output

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