Hollow Hexagon with Numbers

This program prints a hollow hexagon using numbers.

Problem Statement

Write a Java program that prints a hollow hexagon with numbers up to 7 rows.

Source Code

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

Program Output

      1 1 1 1 1 1 1 
     2           2 
    3           3 
   4           4 
  5           5 
 6           6 
7 7 7 7 7 7 7 

Explanation

Similar to the hollow star hexagon, boundary cells print the current row index instead of a star, so each row's number appears at the hexagon's edges creating a hollow numeric hexagon.

Quick Links to Explore