Palindromic Alphabet Pyramid in Java

What You’ll Learn
Each row is a palindrome built from the alphabet: climb from A to the row letter, then step back down without repeating the peak.
Contrast program 17 (reverse line with a diagonal *) and program 1 (only the left half triangle).
⭐ Pattern Output
Five rows, no spaces between letters:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBAComplete Java Program (A–E)
First loop prints A..i. Second prints (i-1)..A, so the peak letter appears only once per row.
public class Main {
public static void main(String[] args) {
int i, j, k;
for (i = 65; i <= 69; i++) {
for (j = 65; j <= i; j++) {
System.out.print((char) j);
}
for (k = i - 1; k >= 65; k--) {
System.out.print((char) k);
}
System.out.println();
}
}
}🧠 How It Works
Outer i
Row peak letter: A through E.
j prints the left half
Ascending letters from A up to i (including the peak).
k = i - 1 prints the mirror
Descending letters from one before the peak back to A, so the middle letter is not doubled.
Why row 1 is just A
When i is 65 ('A'), the second loop starts at 64 and fails immediately, so nothing extra is printed.
Total characters
Row lengths are 1, 3, 5, 7, 9, summing to 25 = 5² for five rows.
Variation — User Input
endChar = (char)('A' + rows - 1) sets the bottom peak. Clamp rows to 1–26.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = sc.nextInt();
rows = Math.max(1, Math.min(rows, 26));
char endChar = (char) ('A' + rows - 1);
for (char i = 'A'; i <= endChar; i++) {
for (char j = 'A'; j <= i; j++) {
System.out.print(j);
}
for (char k = (char) (i - 1); k >= 'A'; k--) {
System.out.print(k);
}
System.out.println();
}
sc.close();
}
}💡 Tips for Enhancement
Try These
- Add leading spaces to center each row like a pyramid on screen
- Use spaced-out letters by outputting a trailing space
- Keep
rows <= 26for capital English letters
Avoid
- Starting the second loop at
i(it doubles the middle letter) - Using
k = ion the downward pass instead ofi - 1
Key Takeaways
Ascending then descending halves build a palindrome.
k = i - 1 avoids printing the peak twice.
Total length for n rows: n² characters.
O(n²) time for n rows.
❓ Frequently Asked Questions
i = 'A', the second loop initializes k = i - 1, which is below 'A', so the condition fails immediately.1 + 3 + ... + (2n-1) = n².'a' and set endChar in the lowercase range; the same loop structure applies.More Java alphabet patterns
Splitting “up then down” is the standard way to code palindromes over a fixed alphabet slice.
When i = 'A' (65), k = i - 1 is 64, so k >= 'A' fails immediately — no extra if needed for the first row.
12 people found this page helpful
