Numeric Spiral with Gaps
This program prints numbers in spiral form with gaps.
Problem Statement
Write a Java program that prints a 5x5 spiral numeric pattern with gaps.
Source Code
| 1 | public class NumericSpiralGaps { |
| 2 | public static void main(String[] args) { |
| 3 | int n = 5; |
| 4 | int[][] arr = new int[n][n]; |
| 5 | int top=0, left=0, bottom=n-1, right=n-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<n; i++) { |
| 17 | for(int j=0; j<n; j++) { |
| 18 | if(arr[i][j]%2==0) System.out.print(arr[i][j] + " "); |
| 19 | else System.out.print(" "); |
| 20 | } |
| 21 | System.out.println(); |
| 22 | } |
| 23 | } |
| 24 | } |
Program Output
2 4
16 18 6
24 20 7
14 22 21 8
12 10
Explanation
The spiral numbers are filled as before, but the printing step only shows even numbers, replacing odd numbers with blank spaces, creating a spiral pattern with visible gaps.