Spiral Pyramid of Numbers

This program prints a pyramid filled with numbers in spiral order.

Problem Statement

Write a Java program that prints a pyramid of numbers arranged in spiral order with 5 rows.

Source Code

1 public class SpiralPyramidNumbers {
2 public static void main(String[] args) {
3 int n = 5, num=1;
4 int[][] arr = new int[n][2*n-1];
5 int top=0, left=n-1, bottom=n-1, right=n-1+(n-1);
6 while(top<=bottom && left<=right) {
7 for(int i=left; i<=right; i++) arr[top][i]=num++;
8 top++;
9 for(int i=top; i<=bottom; i++) arr[i][right]=num++;
10 right--;
11 for(int i=right; i>=left; i--) arr[bottom][i]=num++;
12 bottom--;
13 for(int i=bottom; i>=top; i--) arr[i][left]=num++;
14 left++;
15 }
16 for(int i=0; i<n; i++) {
17 for(int j=0; j<2*n-1; j++) {
18 if(arr[i][j]!=0) System.out.print(arr[i][j] + " ");
19 else System.out.print(" ");
20 }
21 System.out.println();
22 }
23 }
24 }

Program Output

    1 2 3 4 5     
   16          6   
  15 24 25 20 7   
  14 23 22 21 8   
  13 12 11 10 9   

Explanation

A trapezoid-shaped matrix is used with boundaries starting from the middle, and the standard spiral fill logic runs on this matrix so that when printed, unused cells remain blank producing a pyramid outline filled with spiral numbers.

Quick Links to Explore