Spiral Alphabet Pattern
This program prints alphabets arranged in a spiral inside a square.
Problem Statement
Write a Java program that prints a 5x5 spiral alphabet pattern.
Source Code
| 1 | public class SpiralAlphabetPattern { |
| 2 | public static void main(String[] args) { |
| 3 | int n = 5; |
| 4 | char[][] arr = new char[n][n]; |
| 5 | int top=0, left=0, bottom=n-1, right=n-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 | } |
| 17 | for(int i=0; i<n; i++) { |
| 18 | for(int j=0; j<n; j++) System.out.print(arr[i][j] + "\t"); |
| 19 | System.out.println(); |
| 20 | } |
| 21 | } |
| 22 | } |
Program Output
A B C D E P Q R S F O X Y T G N W V U H M L K J I
Explanation
The same spiral boundary logic as the numeric spiral is used, but a character variable ch='A' increments each time instead of a number, so alphabets fill the spiral order across the shrinking boundaries.