Palindromic Alphabet Pyramid in C++

What You’ll Learn
Each row is a palindrome built from two parts: a descending run (i down to B) and an ascending run (A up to i).
This program prints letters with no extra spaces (unlike right-aligned patterns that use a fixed-width grid).
⭐ Pattern Output
Output for 5 rows:
A
BAB
CBABC
DCBABCD
EDCBABCDEC++ Program (Reference Logic)
Same logic as the reference: two loops per row to build the palindrome.
#include <iostream>
using namespace std;
int main() {
int i, j;
for (i = 65; i <= 69; i++) {
for (j = i; j > 65; j--)
cout << char(j);
for (j = 65; j <= i; j++)
cout << char(j);
cout << "\n";
}
return 0;
}🧠 How It Works
Outer i is the peak letter (ASCII)
i runs 65…69 (A…E). That value is both the highest letter on the row and the pivot between the descending and ascending halves.
Left wing: j from i down while j > 65
cout << char(j) prints i, then i-1, … down to B. Stopping above 65 skips the first A so it can appear once in the next loop.
Right wing: j from 65 up to i
The second loop prints A through i inclusive. Together with the left wing you get an odd-length palindrome such as CBABC when i == 'C'.
First row edge case
When i == 65, the descending loop body never runs; the ascending loop prints only A. That matches the single-letter first line of the sample output.
Odd-length rows
Row length is 2 × (i - 65) + 1. Summing over n rows gives O(n²) characters from two inner passes per outer iteration.
Variation — User Input
Read rows and compute endChar as 'A' + rows - 1.
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter the number of rows: ";
cin >> rows;
char startChar = 'A';
char endChar = char('A' + rows - 1);
for (char i = startChar; i <= endChar; ++i) {
for (char j = i; j > startChar; --j) cout << j;
for (char j = startChar; j <= i; ++j) cout << j;
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Insert spaces between letters (then update the output preview)
- Center the pyramid by printing leading spaces based on the widest row
- Validate
rowssoendCharstays withinA..Z
Avoid
- Using
j >= 'A'in the descending loop without removingAfrom the ascending loop - Letting
rowspush output pastZwithout handling it
Key Takeaways
The descending loop stops before A, so the center character is printed once.
Each row is an odd-length palindrome: lengths 1, 3, 5, …
Total characters printed across n rows is n².
O(n²) time for n rows.
❓ Frequently Asked Questions
A. Stopping early prevents a double A in the middle.r (0-based), print (n - r - 1) spaces first.n² characters.Explore More C++ Alphabet Patterns!
Palindromic rows are a great way to practice nested loops and loop boundaries.
The first n odd numbers sum to n², which matches the total characters printed across n rows in this pattern.
12 people found this page helpful
