Palindromic Alphabet Pyramid in C++

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 C++ Program (Reference Logic)
First loop prints A..i. Second prints (i-1)..A, so the peak letter appears only once per row.
#include <iostream>
using namespace std;
int main() {
int i, j, k;
for (i = 65; i <= 69; i++) {
for (j = 65; j <= i; j++)
cout << char(j);
for (k = i - 1; k >= 65; k--)
cout << char(k);
cout << "\n";
}
return 0;
}🧠 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 A (65), 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 = 'A' + rows - 1 sets the bottom peak.
#include <iostream>
using namespace std;
int main() {
int rows;
int i, j, k;
char endChar;
cout << "Enter the number of rows: ";
cin >> rows;
endChar = (char)('A' + rows - 1);
for (i = 'A'; i <= endChar; ++i) {
for (j = 'A'; j <= i; ++j) {
cout << (char) j;
}
for (k = i - 1; k >= 'A'; --k) {
cout << (char) k;
}
cout << "\n";
}
return 0;
}💡 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 an unsigned type for
kwheni == 'A'(underflow can break the stop condition)
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.Explore More C++ 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
