Spiral Pyramid of Alphabets

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

Problem Statement

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

Source Code

1 public class SpiralPyramidAlphabets {
2 public static void main(String[] args) {
3 int n = 5;
4 char[][] arr = new char[n][2*n-1];
5 int top=0, left=n-1, bottom=n-1, right=n-1+(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<2*n-1; 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     
   P         F   
  O X Y T G   
 N W V U H   
 M L K J I   

Explanation

The same trapezoid pyramid spiral matrix is used, but a character variable ch='A' fills each boundary position instead of a number, so the pyramid outline is spelled out with sequential alphabets.

Quick Links to Explore