Alphabet Diamond Pattern
This program prints a diamond pattern using alphabets.
Problem Statement
Write a Java program that prints an alphabet diamond with 5 rows.
Source Code
| 1 | public class AlphabetDiamond { |
| 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(char ch='A'; ch<'A'+i; ch++) System.out.print(ch); |
| 7 | for(char ch=(char)('A'+i-2); ch>='A'; ch--) System.out.print(ch); |
| 8 | System.out.println(); |
| 9 | } |
| 10 | for(int i=n-1; i>=1; i--) { |
| 11 | for(int j=i; j<n; j++) System.out.print(" "); |
| 12 | for(char ch='A'; ch<'A'+i; ch++) System.out.print(ch); |
| 13 | for(char ch=(char)('A'+i-2); ch>='A'; ch--) System.out.print(ch); |
| 14 | System.out.println(); |
| 15 | } |
| 16 | } |
| 17 | } |
Program Output
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDCBA
ABCBA
ABA
A
Explanation
The first loop builds an alphabet pyramid and the second builds an inverted alphabet pyramid, both printing ascending then descending alphabets per row, together forming a symmetric diamond of characters.