Spiral Rectangle of Numbers
This program prints a rectangular spiral of numbers.
Problem Statement
Write a Java program that prints a 4x6 rectangle filled with numbers in spiral order.
Source Code
| 1 | public class SpiralRectangleNumbers { |
| 2 | public static void main(String[] args) { |
| 3 | int rows=4, cols=6; |
| 4 | int[][] arr=new int[rows][cols]; |
| 5 | int top=0, left=0, bottom=rows-1, right=cols-1, num=1; |
| 6 | while(top<=bottom && left<=right) { |
| 7 | for(int i=left; i<=right; i++) arr[top][i]=num++; |
| 8 | top++; |
| 9 | for(int i=top; i<=bottom; i++) arr[i][right]=num++; |
| 10 | right--; |
| 11 | for(int i=right; i>=left; i--) arr[bottom][i]=num++; |
| 12 | bottom--; |
| 13 | for(int i=bottom; i>=top; i--) arr[i][left]=num++; |
| 14 | left++; |
| 15 | } |
| 16 | for(int i=0; i<rows; i++) { |
| 17 | for(int j=0; j<cols; j++) System.out.print(arr[i][j] + "\t"); |
| 18 | System.out.println(); |
| 19 | } |
| 20 | } |
| 21 | } |
Program Output
1 2 3 4 5 6 14 15 16 17 18 7 13 20 19 22 21 8 12 11 10 9 24 23
Explanation
The same spiral fill logic as the square version is applied to a non-square 4x6 matrix, showing that spiral logic adapts naturally to rectangular grids of different row and column counts.