Spiral Hourglass of Numbers and Alphabets
This program prints an hourglass filled with numbers and alphabets in spiral order.
Problem Statement
Write a Java program that prints an hourglass of 7 rows where spiral order alternates numbers and alphabets.
Source Code
| 1 | public class SpiralHourglassNumbersAlphabets { |
| 2 | public static void main(String[] args) { |
| 3 | int n = 7; |
| 4 | String[][] arr = new String[n][n]; |
| 5 | int top=0, left=0, bottom=n-1, right=n-1; |
| 6 | int num=1; char ch='A'; boolean number=true; |
| 7 | while(top<=bottom && left<=right) { |
| 8 | for(int i=left; i<=right; i++) arr[top][i]=number?String.valueOf(num++):String.valueOf(ch++); |
| 9 | number=!number; top++; |
| 10 | for(int i=top; i<=bottom; i++) arr[i][right]=number?String.valueOf(num++):String.valueOf(ch++); |
| 11 | number=!number; right--; |
| 12 | for(int i=right; i>=left; i--) arr[bottom][i]=number?String.valueOf(num++):String.valueOf(ch++); |
| 13 | number=!number; bottom--; |
| 14 | for(int i=bottom; i>=top; i--) arr[i][left]=number?String.valueOf(num++):String.valueOf(ch++); |
| 15 | number=!number; left++; |
| 16 | } |
| 17 | for(int i=0; i<n; i++) { |
| 18 | for(int j=0; j<n; j++) { |
| 19 | if(i<=j && i+j>=n-1) System.out.print(arr[i][j] + " "); |
| 20 | else System.out.print(" "); |
| 21 | } |
| 22 | System.out.println(); |
| 23 | } |
| 24 | } |
| 25 | } |
Program Output
1 A 3 B 5 C 7
D 9 E 11 F 13
15 G 17 H 19
21 I 23
25 J
27
K
Explanation
A boolean flag toggles each boundary loop between filling with sequential numbers or sequential alphabets, and the hourglass printing condition reveals only the shape's relevant cells from this hybrid spiral.