Spiral Hybrid with Diagonal Numbers
This program prints a spiral of stars with numbers on diagonals.
Problem Statement
Write a Java program that prints a 7x7 spiral of stars with numbers placed on diagonals.
Source Code
| 1 | public class SpiralHybridDiagonalNumbers { |
| 2 | public static void main(String[] args) { |
| 3 | int n = 7; |
| 4 | char[][] arr = new char[n][n]; |
| 5 | int top=0, left=0, bottom=n-1, right=n-1; |
| 6 | while(top<=bottom && left<=right) { |
| 7 | for(int i=left; i<=right; i++) arr[top][i]='*'; |
| 8 | top++; |
| 9 | for(int i=top; i<=bottom; i++) arr[i][right]='*'; |
| 10 | right--; |
| 11 | for(int i=right; i>=left; i--) arr[bottom][i]='*'; |
| 12 | bottom--; |
| 13 | for(int i=bottom; i>=top; i--) arr[i][left]='*'; |
| 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(i+1 + " "); |
| 19 | else System.out.print(arr[i][j] + " "); |
| 20 | } |
| 21 | System.out.println(); |
| 22 | } |
| 23 | } |
| 24 | } |
Program Output
1 * * * * * 7 * 2 * * * 6 * * * 3 * 5 * * * * * 4 * * * * * 5 * 3 * * * 6 * * * 2 * 7 * * * * * 1
Explanation
The spiral outline is filled with stars, and the diagonal condition then overlays the row index at diagonal cells, combining the spiral star outline with a numeric diagonal cross.