Spiral Star-Number Hybrid

This program prints a spiral pattern alternating stars and numbers.

Problem Statement

Write a Java program that prints a 5x5 spiral where odd positions are stars and even positions are numbers.

Source Code

1 public class SpiralStarNumberHybrid {
2 public static void main(String[] args) {
3 int n = 5;
4 String[][] arr = new String[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%2==0)?String.valueOf(num++):"*";
8 top++;
9 for(int i=top; i<=bottom; i++) arr[i][right]=(num%2==0)?String.valueOf(num++):"*";
10 right--;
11 for(int i=right; i>=left; i--) arr[bottom][i]=(num%2==0)?String.valueOf(num++):"*";
12 bottom--;
13 for(int i=bottom; i>=top; i--) arr[i][left]=(num%2==0)?String.valueOf(num++):"*";
14 left++;
15 }
16 for(int i=0; i<n; i++) {
17 for(int j=0; j<n; j++) System.out.print(arr[i][j] + "\t");
18 System.out.println();
19 }
20 }
21 }

Program Output

*   2   *   4   *   
*   10  12  14  6   
*   18  *   16  8   
*   20  22  24  10  
*   *   *   *   *   

Explanation

The spiral logic fills positions sequentially, and the condition (num%2==0) decides whether a position holds a number or a star, so the spiral alternates between symbols based on parity of the running count.

Quick Links to Explore