Numeric Hourglass Pattern

This program prints an hourglass pattern with numbers.

Problem Statement

Write a Java program that prints an hourglass pattern with numbers up to 5 rows.

Source Code

1 public class NumericHourglass {
2 public static void main(String[] args) {
3 int n = 5;
4 for(int i=n; i>=1; i--) {
5 for(int j=n; j>i; j--) System.out.print(" ");
6 for(int j=1; j<=2*i-1; j++) System.out.print(i);
7 System.out.println();
8 }
9 for(int i=2; i<=n; i++) {
10 for(int j=n; j>i; j--) System.out.print(" ");
11 for(int j=1; j<=2*i-1; j++) System.out.print(i);
12 System.out.println();
13 }
14 }
15 }

Program Output

555555555 
 4444444  
  33333   
   222    
    1     
   222    
  33333   
 4444444  
555555555 

Explanation

Similar to the star hourglass, the first loop builds an inverted numeric pyramid and the second builds an upright numeric pyramid, but each row repeats its own row index instead of stars, forming a numeric hourglass shape.

Quick Links to Explore