Hollow Diamond of Stars
This program prints a hollow diamond of stars.
Problem Statement
Write a Java program that prints a hollow diamond of stars with 5 rows.
Source Code
| 1 | public class HollowDiamond { |
| 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) System.out.print("*"); |
| 8 | else System.out.print(" "); |
| 9 | } |
| 10 | System.out.println(); |
| 11 | } |
| 12 | for(int i=n-1; i>=1; i--) { |
| 13 | for(int j=i; j<n; j++) System.out.print(" "); |
| 14 | for(int k=1; k<=2*i-1; k++) { |
| 15 | if(k==1 || k==2*i-1) System.out.print("*"); |
| 16 | else System.out.print(" "); |
| 17 | } |
| 18 | System.out.println(); |
| 19 | } |
| 20 | } |
| 21 | } |
Program Output
*
* *
* *
* *
* *
* *
* *
* *
*
Explanation
The first half builds an upper hollow pyramid and the second builds an inverted hollow pyramid, printing stars only at boundaries with spaces inside, together forming a hollow diamond shape.