Spiral Trapezoid of Alphabets

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

Problem Statement

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

Source Code

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

Program Output

A B C D E F G H I 
R               J 
Q Z A B C K     
P Y X W D L     
O N M L K       

Explanation

The same trapezoid-shaped spiral fill is used as the numeric version, but a rotating alphabet character fills each boundary cell, resetting after 'Z', so the trapezoid outline is spelled out with recurring letters.

Quick Links to Explore