Spiral Trapezoid of Numbers

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

Problem Statement

Write a Java program that prints a trapezoid of 5 rows filled with numbers in spiral order.

Source Code

1 public class SpiralTrapezoidNumbers {
2 public static void main(String[] args) {
3 int rows=5, cols=9;
4 int[][] arr=new int[rows][cols];
5 int top=0, left=0, bottom=rows-1, right=cols-1, num=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<rows;i++){
17 for(int j=0;j<cols;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 6 7 8 9 
18             10 
17 24 25 26 27 11 
16 23 22 21 12    
15 14 13          

Explanation

The standard rectangular spiral fill logic is applied to a wider 5x9 matrix, and since not every cell gets filled by the spiral in this shape, unfilled cells remain zero and are printed as blanks, giving a trapezoid-like appearance.

Quick Links to Explore