Mirror Number Pyramid in C++

What You’ll Learn
How to print a mirror number pyramid in C++ such as 32123 and 543212345.
Each row is built in two parts: a descending sequence from i down to 2, followed by an ascending sequence from 1 up to i.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
212
32123
4321234
543212345Complete C++ Program
Two inner loops: one prints the left (descending) half, the other prints the right (ascending) half.
#include <iostream>
using namespace std;
int main() {
int rows = 5;
int i, j;
for (i = 1; i <= rows; i++) {
for (j = i; j > 1; j--) {
cout << j;
}
for (j = 1; j <= i; j++) {
cout << j;
}
cout << "\n";
}
return 0;
}🧠 How It Works
Choose the row count
rows = 5 sets how many lines will be printed.
Outer loop controls the row
for (i = 1; i <= rows; i++) moves from row 1 to row rows.
Print the descending half
for (j = i; j > 1; j--) prints i, i-1, ..., 2.
Print the ascending half
for (j = 1; j <= i; j++) prints 1, 2, ..., i right after the descending half.
Mirror number pyramid
Row i prints 2i-1 digits, so total work across all rows is O(n²).
Variation — User Input Version
Let the user choose the number of rows using cin:
#include <iostream>
using namespace std;
int main() {
int rows;
int i, j;
cout << "Enter the number of rows: ";
cin >> rows;
for (i = 1; i <= rows; i++) {
for (j = i; j > 1; j--) {
cout << j;
}
for (j = 1; j <= i; j++) {
cout << j;
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Add spaces between numbers for readability (e.g., print
j << ' ') - Right-align the pyramid by printing leading spaces before each row
- Start from a different peak value (use a base offset in the printed numbers)
- Print characters instead of numbers to make an alphabet mirror pattern
- Build each row into a string for easier formatting
Avoid
- Printing the center
1twice (ensure the left loop stops at 2) - Using negative or zero rows without validation
- Forgetting the newline after each row
- Overcomplicating the logic—two simple loops are enough
Key Takeaways
Each row is made from a descending part and an ascending part.
The descending loop prints i..2, so the center 1 appears only once.
Row i prints 2i-1 digits (odd length), creating the mirror effect.
Total time grows quadratically with rows: O(n²).
❓ Frequently Asked Questions
j > 1 so that the center 1 is printed only once by the second loop.rows - i before the two loops. That shifts the pyramid toward the center.2i-1 characters.Explore More C++ Number Patterns!
Try combining mirror logic with spacing and alignment to build more pyramid-style patterns.
Many “palindrome” patterns are just two loops back-to-back: one loop for the left side and another for the right side. Keeping them separate makes the logic easier to reason about.
12 people found this page helpful
