Reverse Counting Number Triangle in C++

What You’ll Learn
How to print a triangle where each row counts down from the row number to 1.
This helps practice loop boundaries and reverse counting with nested loops.
⭐ Pattern Output
For rows = 5, the output looks like this:
1
21
321
4321
54321Complete C++ Program
The inner loop counts down from i to 1 on each row.
#include <iostream>
using namespace std;
int main() {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = i; j >= 1; j--) {
cout << j;
}
cout << "\n";
}
return 0;
}🧠 How It Works
Set the number of rows
int rows = 5; controls the height of the triangle.
Outer loop (row number)
for (int i = 1; i <= rows; i++) moves from row 1 to row 5.
Inner loop (count down)
for (int j = i; j >= 1; j--) prints i, i-1, ..., 1.
New line
cout << "\n"; moves the cursor to the next row.
Reverse counting triangle
Total prints are \(1 + 2 + \dots + n\) = n(n+1)/2, so time complexity is O(n²).
Variation — User Input Version
Read the number of rows at runtime using cin:
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter the number of rows: ";
cin >> rows;
for (int i = 1; i <= rows; i++) {
for (int j = i; j >= 1; j--) {
cout << j;
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Add spaces:
cout << j << ' '; - Print a mirrored version by appending an ascending loop after the countdown
- Validate input (check
cin.fail()) for robustness - Change the outer loop direction to create other triangle orientations
Avoid
- Forgetting the newline after each row (output will run together)
- Using the wrong loop bounds (e.g., stopping at 0 won’t print 1)
- Negative/zero rows (handle with a guard if needed)
Key Takeaways
The outer loop chooses the row number i.
The inner loop counts down from i to 1.
Each row prints exactly i digits, so total prints are \(n(n+1)/2\).
This is a clean exercise for reverse loops and triangle shapes.
❓ Frequently Asked Questions
i from rows down to 1, instead of 1 up to rows.\n is usually faster because endl flushes the stream.Explore More C++ Number Patterns!
Try mixing reverse loops and spacing to build new triangle patterns.
Reverse loops (counting down) are frequently used in pattern printing and array traversal problems.
12 people found this page helpful
