Spiral Rectangle Hybrid (Numbers + Alphabets)
This program prints a rectangular spiral alternating numbers and alphabets.
Problem Statement
Write a Java program that prints a 5x7 rectangle where spiral order alternates numbers and alphabets.
Source Code
| 1 | public class SpiralRectangleNumbersAlphabets { |
| 2 | public static void main(String[] args) { |
| 3 | int rows=5, cols=7, num=1; |
| 4 | String[][] arr=new String[rows][cols]; |
| 5 | int top=0, left=0, bottom=rows-1, right=cols-1; |
| 6 | 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 | if(ch>'Z') ch='A'; |
| 17 | } |
| 18 | for(int i=0; i<rows; i++) { |
| 19 | for(int j=0; j<cols; j++) System.out.print(arr[i][j] + "\t"); |
| 20 | System.out.println(); |
| 21 | } |
| 22 | } |
| 23 | } |
Program Output
1 A 2 B 3 C 4 N O P Q R S 5 M Z A B C T 6 L Y X W D U 7 K J I H G F E
Explanation
A boolean toggle alternates each boundary loop between filling with sequential numbers and sequential alphabets, and the alphabet character resets after 'Z', producing a rectangular spiral hybrid of numbers and letters.