Rotating Start Number Pattern in C++

What You’ll Learn
How to print a pattern where each row starts with a descending prefix and then continues with ascending numbers:
12345, 21234, 32123, 43212, 54321.
This is a neat nested-loop exercise that combines descending and ascending sequences.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
21234
32123
43212
54321Complete C++ Program
First print i..2, then print 1..(rows+1-i).
#include <iostream>
using namespace std;
int main() {
int i, j, k;
for (i = 1; i <= 5; i++) {
for (j = i; j > 1; j--)
cout << j;
for (k = 1; k <= 6 - i; k++)
cout << k;
cout << "\n";
}
return 0;
}🧠 How It Works
Outer loop chooses the row
i runs from 1 to 5, creating 5 rows.
Print the descending prefix
The first inner loop prints i, i-1, ... , 2. For i=4, it prints 432.
Print the ascending suffix
The second inner loop prints 1..(rows+1-i). For i=4, it prints 12.
Combine both parts
Together, the row becomes 432 + 12 = 43212.
Rotating start
Each row keeps total length 5 while shifting the start digit forward.
Variation — User Input Version
Let the user choose the number of rows and print the same logic for any rows.
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter the number of rows: ";
cin >> rows;
if (rows <= 0) return 0;
for (int i = 1; i <= rows; i++) {
for (int j = i; j > 1; j--)
cout << j;
for (int k = 1; k <= (rows + 1 - i); k++)
cout << k;
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Add spaces between digits for readability
- Print the pattern with leading spaces to make it a pyramid
- Replace digits with letters for an alphabet version
- Validate input (check
cin.fail()) - Create a mirror variant by changing the suffix direction
Avoid
- Hard-coding 5 if you want a reusable program
- Forgetting the newline after each row
- Using
endlin loops (extra flushing) - Mixing row/column logic (keep row in outer loop)
Key Takeaways
Row i prints a descending prefix from i to 2.
Then it prints an ascending suffix from 1 to rows+1-i.
Total row length stays constant (equal to rows).
Overall work is about O(n²) for n rows.
❓ Frequently Asked Questions
i-1 digits (from i down to 2) and the suffix prints rows-i+1 digits (from 1 to that value). Together they total rows.i from rows down to 1 to reverse the row order.Explore More C++ Number Patterns!
Combining descending and ascending loops is a common trick for many “rotation” style patterns.
You can think of each row as a small rotation: print backwards from i to 2, then wrap around and print from 1 upward.
12 people found this page helpful
