Hollow Pyramid of Stars
This program prints a hollow pyramid of stars.
Problem Statement
Write a Java program that prints a hollow pyramid of stars with 5 rows.
Source Code
| 1 | public class HollowPyramid { |
| 2 | public static void main(String[] args) { |
| 3 | int n = 5; |
| 4 | for(int i=1; i<=n; i++) { |
| 5 | for(int j=i; j<n; j++) System.out.print(" "); |
| 6 | for(int k=1; k<=2*i-1; k++) { |
| 7 | if(k==1 || k==2*i-1 || i==n) { |
| 8 | System.out.print("*"); |
| 9 | } else { |
| 10 | System.out.print(" "); |
| 11 | } |
| 12 | } |
| 13 | System.out.println(); |
| 14 | } |
| 15 | } |
| 16 | } |
Program Output
* * * * * * * *********
Explanation
Spaces align stars centrally while the inner loop prints stars only at the row boundaries or at the base row (i==n), and spaces elsewhere, creating a hollow pyramid with a filled base.