Hollow Number Pyramid

This program prints a hollow number pyramid.

Problem Statement

Write a Java program that prints a hollow number pyramid with 5 rows.

Source Code

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

Program Output

    1    
   2 2   
  3   3  
 4     4 
555555555

Explanation

The inner loop prints the row index only at the boundaries or the base row, with spaces elsewhere, so each row uses its own row number at the edges creating a hollow numeric pyramid.

Quick Links to Explore