Diamond of Stars
This program prints a diamond of stars.
Problem Statement
Write a Java program that prints a diamond of stars with 5 rows.
Source Code
| 1 | public class DiamondStars { |
| 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++) System.out.print("*"); |
| 7 | System.out.println(); |
| 8 | } |
| 9 | for(int i=n-1; i>=1; i--) { |
| 10 | for(int j=i; j<n; j++) System.out.print(" "); |
| 11 | for(int k=1; k<=2*i-1; k++) System.out.print("*"); |
| 12 | System.out.println(); |
| 13 | } |
| 14 | } |
| 15 | } |
Program Output
*
***
*****
*******
*********
*******
*****
***
*
Explanation
The first outer loop builds the upper pyramid half and the second builds the inverted lower half, with spaces aligning stars centrally so that stars increase then decrease symmetrically to form a diamond shape.