Alphabet Spiral with Stars

This program prints alphabets in spiral form with stars at corners.

Problem Statement

Write a Java program that prints a 5x5 spiral alphabet pattern with stars at corners.

Source Code

1 public class AlphabetSpiralStars {
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 arr[0][0]='*'; arr[0][n-1]='*'; arr[n-1][0]='*'; arr[n-1][n-1]='*';
18 for(int i=0; i<n; i++) {
19 for(int j=0; j<n; j++) System.out.print(arr[i][j] + "\t");
20 System.out.println();
21 }
22 }
23 }

Program Output

*   B   C   D   *   
P   Q   R   S   E   
O   X   Y   T   F   
N   W   V   U   G   
*   L   K   J   *   

Explanation

The spiral is filled with alphabets as usual, then the four corner cells of the array are explicitly overwritten with stars after the spiral fill, combining spiral logic with a fixed corner overlay.

Quick Links to Explore