Spiral Rectangle Hybrid (Stars + Numbers)

This program prints a rectangular spiral alternating stars and numbers.

Problem Statement

Write a Java program that prints a 4x6 rectangle where spiral order alternates stars and numbers.

Source Code

1 public class SpiralRectangleHybrid {
2 public static void main(String[] args) {
3 int rows=4, cols=6, num=1;
4 String[][] arr=new String[rows][cols];
5 int top=0, left=0, bottom=rows-1, right=cols-1;
6 boolean star=true;
7 while(top<=bottom && left<=right) {
8 for(int i=left; i<=right; i++) arr[top][i]=star?"*":String.valueOf(num++);
9 star=!star; top++;
10 for(int i=top; i<=bottom; i++) arr[i][right]=star?"*":String.valueOf(num++);
11 star=!star; right--;
12 for(int i=right; i>=left; i--) arr[bottom][i]=star?"*":String.valueOf(num++);
13 star=!star; bottom--;
14 for(int i=bottom; i>=top; i--) arr[i][left]=star?"*":String.valueOf(num++);
15 star=!star; left++;
16 }
17 for(int i=0; i<rows; i++) {
18 for(int j=0; j<cols; j++) System.out.print(arr[i][j] + "\t");
19 System.out.println();
20 }
21 }
22 }

Program Output

*   2   *   4   *   6   
*   14  *   16  *   8   
*   20  *   18  *   10  
*   *   *   *   *   *   

Explanation

A boolean toggle alternates between star and number fills for each boundary loop of the rectangular spiral, so this rectangular matrix mirrors the earlier hybrid pyramid logic on a non-square shape.

Quick Links to Explore