Double Spiral Number Pattern
This program prints two spirals of numbers inside a square.
Problem Statement
Write a Java program that prints a 6x6 double spiral number pattern.
Source Code
| 1 | public class DoubleSpiralNumber { |
| 2 | public static void main(String[] args) { |
| 3 | int n = 6; |
| 4 | int[][] arr = new int[n][n]; |
| 5 | int num=1; |
| 6 | for(int layer=0; layer<n/2; layer++) { |
| 7 | for(int i=layer; i<n-layer; i++) arr[layer][i]=num++; |
| 8 | for(int i=layer+1; i<n-layer; i++) arr[i][n-layer-1]=num++; |
| 9 | for(int i=n-layer-2; i>=layer; i--) arr[n-layer-1][i]=num++; |
| 10 | for(int i=n-layer-2; i>layer; i--) arr[i][layer]=num++; |
| 11 | } |
| 12 | for(int i=0; i<n; i++) { |
| 13 | for(int j=0; j<n; j++) System.out.print(arr[i][j] + "\t"); |
| 14 | System.out.println(); |
| 15 | } |
| 16 | } |
| 17 | } |
Program Output
1 2 3 4 5 6 20 21 22 23 24 7 19 32 33 34 25 8 18 31 36 35 26 9 17 30 29 28 27 10 16 15 14 13 12 11
Explanation
A layer-based approach loops over concentric layers, filling the top, right, bottom, and left boundaries of each layer sequentially, so a continuous sequence of numbers spirals inward layer by layer.