Java Code Example: Hourglass Pattern

This code prints an hourglass pattern made up of asterisks. The hourglass pattern is created using nested loops, with the first loop controlling the rows and the inner loops controlling the columns.

Code Example

class HourglassPatternExample {
    public static void main(String[] args) {
        int i, j, k, n = 8;

        for (i = 1; i <= n; i++) {
            for (j = 1; j < i; j++) {
                System.out.print(' ');
            }

            for (k = i; k <= n; k++) {
                System.out.print("* ");
            }
            System.out.println();
        }
        for (i = n - 1; i >= 1; i--) {
            for (j = 1; j < i; j++) {
                System.out.print(' ');
            }
            for (k = i; k <= n; k++) {
                System.out.print("* ");
            }

            System.out.println();
        }
    }
}

Output

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

Code Explanation

The variable n represents the number of rows in the hourglass. The outer loop runs from 1 to n and the inner loops run from 1 to i-1 for the spaces and from i to n for the asterisks. The first inner loop is used to print spaces before the asterisks to create the left side of the hourglass pattern. The second inner loop is used to print the asterisks to create the right side of the hourglass pattern.

After the top half of the hourglass pattern is printed, the code prints the bottom half of the hourglass pattern using similar loops, but in reverse order. The outer loop starts at n-1 and runs down to 1, and the inner loops print spaces and asterisks in the opposite order from the top half of the pattern.