Spiral Pyramid of Stars

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

Problem Statement

Write a Java program that prints a pyramid of stars arranged in spiral order with 5 rows.

Source Code

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

Program Output

    * * * * *     
   *         *   
  * * * * * * *  
 *             * 
* * * * * * * * * 

Explanation

The same trapezoid spiral matrix approach is used but every boundary cell is simply marked with a star instead of a number, so the spiral traces a pyramid-shaped outline of stars.

Quick Links to Explore