Right-Aligned Alphabet Pyramid in C++

What You’ll Learn
We use a simple trick: print a shrinking number of leading spaces, then print letters starting from A up to the current row letter.
Because letters use setw(2), use a monospace font if you want the right edge to look perfect.
⭐ Pattern Output
Output for 5 rows:
A
A B
A B C
A B C D
A B C D EC++ Program (Reference Logic)
Fixed range A.. E, with one-space padding and setw(2) letters.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int i, j, k;
for (i = 65; i <= 69; i++) {
for (j = 69; j > i; j--)
cout << " ";
for (k = 65; k <= i; k++)
cout << setw(2) << char(k);
cout << "\n";
}
return 0;
}🧠 How It Works
Outer i
Sets the last letter for the current row: A through E.
Padding loop
Print one space while j > i. That is 'E' - i spaces, shrinking by 1 each row.
Letter loop
Print A.. i using setw(2) so the sample spacing matches.
Constant visual width
Padding shrinks as the letter run grows, so the right margin stays aligned. Combined with <iomanip> width-two letters, the ramp stays readable on narrow viewports.
Example row
At i = 'C', two padding spaces then three setw(2) letters. Five rows × O(n) inner work → O(n²) for n letters.
Variation — User Input
Let the user choose the number of rows. We compute endChar as 'A' + rows - 1 and reuse the same loop structure.
#include <iostream>
#include <iomanip>
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 = endChar; j > i; --j) cout << ' ';
for (char k = startChar; k <= i; ++k) cout << setw(2) << k;
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Left-align the pattern by removing the padding loop
- Use
setw(3)and adjust padding if you want wider columns - Validate
rowsto keep output withinA..Z
Avoid
- Expecting alignment in a proportional font
- Mixing double-space padding with
setw(2)without checking spacing
Key Takeaways
Padding count per row is endChar - i spaces.
Letters per row is i - startChar + 1.
setw(2) matches the spaced sample output.
O(n²) work for n rows.
❓ Frequently Asked Questions
j == i, we want to stop padding and begin printing letters, so the condition is strictly j > i.Explore More C++ Alphabet Patterns!
Once you understand padding and loop bounds, you can build many aligned triangles and pyramids.
Each step down removes one padding space and adds one more letter, so the right edge stays fixed when printed in a monospace font.
12 people found this page helpful
