Right-Aligned Decreasing Number Pattern in C++

What You’ll Learn
How to print a right-aligned triangle where each row starts from 5 and counts down:
5, then 5 4, then 5 4 3, continuing until 5 4 3 2 1.
We’ll use nested loops, indentation spaces, and setw(2) for clean alignment.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1Complete C++ Program
First we print indentation spaces, then we print numbers from 5 down to the current row limit.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int rows = 5;
int i, j;
for (i = rows; i >= 1; i--) {
for (j = 1; j < i; j++) {
cout << " ";
}
for (j = rows; j >= i; j--) {
cout << setw(2) << j;
}
cout << "\n";
}
return 0;
}🧠 How It Works
Set the number of rows
rows = 5 sets both the height and the starting number.
Outer loop counts down
for (i = rows; i >= 1; i--) builds rows from top to bottom.
Indent with spaces
The first inner loop prints 2 * (i - 1) spaces so the numbers align to the right.
Print 5 down to i
The second inner loop prints numbers rows..i using setw(2) for consistent spacing.
Right-aligned decreasing triangle
Total printed numbers are n(n+1)/2, so time complexity is O(n²) for n rows.
Variation — User Input Version
Let the user choose the starting value (rows) using cin:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int rows;
int i, j;
cout << "Enter the starting number (rows): ";
cin >> rows;
for (i = rows; i >= 1; i--) {
for (j = 1; j < i; j++) {
cout << " ";
}
for (j = rows; j >= i; j--) {
cout << setw(2) << j;
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Increase the width in
setw()when printing bigger numbers (e.g.,setw(3)) - Print the ascending version by changing the print loop direction
- Add a separator like a comma to make the output more readable
- Combine with other rules (like printing only odd numbers) to create new patterns
- Convert to left-aligned by removing the indentation loop
Avoid
- Using
endlinside loops (it flushes output and slows printing) - Hard-coding the pattern size in multiple places
- Mixing indentation and number printing without a clear structure
- Forgetting to include
<iomanip>when usingsetw()
Key Takeaways
Indentation spaces make the triangle right-aligned.
The printed values come from a simple loop: rows down to i.
setw(2) keeps spacing uniform for cleaner output.
Total printed numbers are n(n+1)/2 so work is O(n²).
❓ Frequently Asked Questions
setw(2), so printing " " (two spaces) matches the same width and keeps alignment.rows. The outer loop should run from rows down to 1, and the print loop should run j = rows down to i.Explore More C++ Number Patterns!
Try flipping the loop directions or changing the value rule to generate new right-aligned patterns.
Alignment in console output is usually just a combination of padding (spaces) and fixed-width printing (like setw()).
12 people found this page helpful
