Spiral Pyramid Hybrid (Stars + Numbers)

This program prints a pyramid filled with stars and numbers in spiral order.

Problem Statement

Write a Java program that prints a pyramid of 5 rows where spiral order alternates stars and numbers.

Source Code

1 public class SpiralPyramidHybrid {
2 public static void main(String[] args) {
3 int n = 5, num=1;
4 String[][] arr = new String[n][2*n-1];
5 int top=0, left=n-1, bottom=n-1, right=n-1+(n-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<n; i++) {
18 for(int j=0; j<2*n-1; j++) {
19 if(arr[i][j]!=null) System.out.print(arr[i][j] + " ");
20 else System.out.print(" ");
21 }
22 System.out.println();
23 }
24 }
25 }

Program Output

    * 2 * 4 *     
   *         6   
  * * * * * * *  
 *             * 
* * * * * * * * * 

Explanation

A boolean flag star toggles after every boundary loop completes, so each side of the spiral alternates between filling with stars or filling with sequential numbers, creating a hybrid spiral pyramid.

Quick Links to Explore