Spiral Number with Diagonal Stars
This program prints a spiral of numbers with stars along diagonals.
Problem Statement
Write a Java program that prints a 7x7 spiral of numbers with stars placed on both diagonals.
Source Code
| 1 | public class SpiralNumberDiagonalStars { |
| 2 | public static void main(String[] args) { |
| 3 | int n = 7; |
| 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(i==j || i+j==n-1) System.out.print("*\t"); |
| 19 | else System.out.print(arr[i][j] + "\t"); |
| 20 | } |
| 21 | System.out.println(); |
| 22 | } |
| 23 | } |
| 24 | } |
Program Output
* 2 3 4 5 6 * 8 * 10 11 12 * 14 15 16 * 18 * 20 21 22 23 24 * 26 27 28 29 30 * 32 * 34 35 36 * 38 39 40 * 42 * 44 45 46 47 48 *
Explanation
After the spiral matrix of numbers is generated, the printing step checks the diagonal condition i==j || i+j==n-1 and replaces those positions with stars, overlaying a diagonal cross pattern on the spiral.