Spiral Rectangle of Alphabets

This program prints a rectangular spiral of alphabets.

Problem Statement

Write a Java program that prints a 5x7 rectangle filled with alphabets in spiral order.

Source Code

1 public class SpiralRectangleAlphabets {
2 public static void main(String[] args) {
3 int rows=5, cols=7;
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++;
9 top++;
10 for(int i=top; i<=bottom; i++) arr[i][right]=ch++;
11 right--;
12 for(int i=right; i>=left; i--) arr[bottom][i]=ch++;
13 bottom--;
14 for(int i=bottom; i>=top; i--) arr[i][left]=ch++;
15 left++;
16 if(ch>'Z') ch='A';
17 }
18 for(int i=0; i<rows; i++) {
19 for(int j=0; j<cols; j++) System.out.print(arr[i][j] + "\t");
20 System.out.println();
21 }
22 }
23 }

Program Output

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

Explanation

The rectangular spiral matrix is filled with a rotating alphabet character that resets to 'A' after 'Z' at the end of each layer, so the spiral is spelled out with repeating alphabetic sequences on a non-square grid.

Quick Links to Explore