Spiral Hourglass Hybrid (Stars + Alphabets)
This program prints an hourglass filled with stars and alphabets in spiral order.
Problem Statement
Write a Java program that prints an hourglass of 7 rows where spiral order alternates stars and alphabets.
Source Code
| 1 | public class SpiralHourglassHybrid { |
| 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 | char ch='A'; boolean star=true; |
| 7 | while(top<=bottom && left<=right) { |
| 8 | for(int i=left; i<=right; i++) arr[top][i]=star?"*":String.valueOf(ch++); |
| 9 | star=!star; top++; |
| 10 | for(int i=top; i<=bottom; i++) arr[i][right]=star?"*":String.valueOf(ch++); |
| 11 | star=!star; right--; |
| 12 | for(int i=right; i>=left; i--) arr[bottom][i]=star?"*":String.valueOf(ch++); |
| 13 | star=!star; bottom--; |
| 14 | for(int i=bottom; i>=top; i--) arr[i][left]=star?"*":String.valueOf(ch++); |
| 15 | star=!star; 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
* A * C * E *
G * I * K * M
O * Q * S *
U * W *
Y *
A
B
Explanation
A boolean toggle alternates each boundary loop between filling with stars or filling with sequential alphabets, and the hourglass printing condition then reveals only the relevant hourglass-shaped section of this hybrid spiral.