Rotating Alphabet Pattern in C++

What You’ll Learn
Each row is a cyclic rotation of the same set of letters. We print from the row start to the end, then wrap around by printing the earlier letters.
This output uses adjacent letters (no spaces), matching the reference.
⭐ Pattern Output
Output for 5 rows:
ABCDE
BCDEA
CDEBA
DECBA
EDCBAC++ Program (Reference Logic)
Forward run i..E plus wrap run using k - 1.
#include <iostream>
using namespace std;
int main() {
int i, j, k;
for (i = 65; i <= 69; i++) {
for (j = i; j <= 69; j++)
cout << char(j);
for (k = i; k > 65; k--)
cout << char(k - 1);
cout << "\n";
}
return 0;
}🧠 How It Works
Outer i is the rotation start
Each row picks a new leading letter from A to E. The line is still a permutation of the same block A…E, only rotated so a different letter leads.
Forward leg: j from i to E
cout << char(j) prints the suffix from the row start through the top letter (e.g. BCDE when i == 'B').
Wrap leg: k with char(k - 1)
for (k = i; k > 65; k--) prints char(k - 1) each time, emitting i-1, i-2, … down to A without repeating the first letter of the forward segment.
Why every row has five letters
Forward part length 'E' - i + 1 plus wrap part i - 'A' sums to 'E' - 'A' + 1 for this fixed alphabet slice.
Cyclic shifts
Each row is a rotation of ABCDE. Two inner passes per outer row → O(n²) prints for n letters in the block.
Variation — User Input
Generalize the block size with rows (so letters range A.. char('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 <= endChar; ++j) cout << j;
for (char k = i; k > startChar; --k) cout << char(k - 1);
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Add a space after each letter for readability
- Validate
rowssoendCharstays withinA..Z - Implement rotation using an array + modulo indexing for larger alphabets
Avoid
- Printing
k(notk - 1) in the wrap loop (duplicates the first letter) - Letting
rowsexceed 26 without handling non-letter ASCII values
Key Takeaways
Forward: i..end, then wrap: (i-1)..start.
Using k - 1 prevents duplicating the row’s first letter.
Every row has the same length: endChar - startChar + 1.
O(n²) total output for n letters.
❓ Frequently Asked Questions
i. The wrap should continue with the letter before i, not repeat i again.i = A, the wrap loop does not run, so the row is just ABCDE.Explore More C++ Alphabet Patterns!
This is a compact way to generate cyclic shifts without arrays.
If you imagine A B C D E written on a circle, each row is just reading from a different starting point.
12 people found this page helpful
