Rotating Mirror Number Pattern in C++

What You’ll Learn
How to print a pattern where each row starts at i, counts up to rows, and then appends the missing digits by counting down to 1.
This produces:
12345, 23451, 34521, 45321, 54321.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
23451
34521
45321
54321Complete C++ Program
Two loops per row: first prints the increasing tail (i..rows), second prints the decreasing head (i-1..1).
#include <iostream>
using namespace std;
int main() {
int rows = 5;
int i, j, k;
for (i = 1; i <= rows; i++) {
for (j = i; j <= rows; j++) {
cout << j;
}
for (k = i; k > 1; k--) {
cout << (k - 1);
}
cout << "\n";
}
return 0;
}🧠 How It Works
Set the size
rows = 5 is the maximum digit printed in each row.
Outer loop chooses the row start
i runs from 1 to rows. Each row begins from the current i.
Print i..rows
The first inner loop prints i, i+1, ..., rows. Example: when i=3, it prints 345.
Append (i-1)..1
The second inner loop appends i-1, i-2, ..., 1. For i=3, it appends 21, giving 34521.
Rotating mirror rows
Each row prints rows digits, so the total work is O(n²) for n rows.
Variation — User Input Version
Let the user choose rows using cin:
#include <iostream>
using namespace std;
int main() {
int rows;
int i, j, k;
cout << "Enter the value of rows: ";
cin >> rows;
for (i = 1; i <= rows; i++) {
for (j = i; j <= rows; j++) {
cout << j;
}
for (k = i; k > 1; k--) {
cout << (k - 1);
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Add spaces between digits for readability
- Use a different range (e.g., 1..9) by changing
rows - Left-pad each row to create a centered look
- Print the same logic with characters (A..E) instead of numbers
- Store each row in a string to simplify separators
Avoid
- Hard-coding
5everywhere instead of usingrows - Printing 0 or negative rows without validation
- Forgetting the newline after each row
- Mixing loop roles (keep one loop for increasing and one for decreasing)
Key Takeaways
The first inner loop prints i..rows.
The second inner loop prints i-1..1 to fill the missing part.
Together they create rotating rows like 23451 and 34521.
Overall work is O(n²) for n rows.
❓ Frequently Asked Questions
rows-i+1 digits and the second prints i-1 digits. Their sum is always rows.i = rows, the first loop prints only rows (5). The second loop appends 4,3,2,1, producing 54321.Explore More C++ Number Patterns!
Once you understand loop bounds, you can create many rotating and mirrored number designs.
You can view this as a simple “rotation”: print from i to rows, then wrap around and print from 1 upward (here, achieved by printing i-1 down to 1).
12 people found this page helpful
