Inverted Repeating Number Triangle in C++

What You’ll Learn
How to print an inverted repeating number triangle in C++. Each row repeats the same digit (the row number), and the number of digits decreases every line: 55555, 4444, 333, 22, 1.
This is a great nested-loop exercise: the outer loop controls the current digit, while the inner loop controls how many times that digit is printed.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
55555
4444
333
22
1Complete C++ Program
The outer loop counts down from rows to 1. The inner loop repeats the current row value i exactly i times.
#include <iostream>
using namespace std;
int main() {
int rows = 5;
int i, j;
for (i = rows; i >= 1; i--) {
for (j = 1; j <= i; j++) {
cout << i;
}
cout << "\n";
}
return 0;
}🧠 How It Works
Choose the size
int rows = 5; sets both the first digit and the height of the triangle.
Outer loop (count down)
for (i = rows; i >= 1; i--) picks the digit to print on each row: 5, 4, 3, 2, 1.
Inner loop (repeat i)
for (j = 1; j <= i; j++) prints the same number i exactly i times using cout << i.
New line
cout << "\n"; completes one row before moving to the next.
Inverted repeating triangle
Total digits printed: 1+2+…+n = n(n+1)/2, so time complexity is O(n²) for n rows.
Variation — User Input Version
Let the user choose the size of the triangle at runtime using cin:
#include <iostream>
using namespace std;
int main() {
int rows;
int i, j;
cout << "Enter the number of rows: ";
cin >> rows;
for (i = rows; i >= 1; i--) {
for (j = 1; j <= i; j++) {
cout << i;
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Validate user input (e.g., check
cin.fail()) before usingrows - Add spaces for readability:
cout << i << ' '; - Right-align the triangle by printing leading spaces before each row
- Replace digits with characters (A, B, C...) to build alphabet patterns
- Print the non-repeating version by outputting
jinstead ofi
Avoid
- Forgetting to print a newline after each row
- Using
endlinside loops (it flushes and can slow output) - Mixing row and column logic (keep outer = digit/row, inner = repeats)
- Allowing
rows <= 0without handling it
Key Takeaways
The outer loop counts down from rows to 1, setting the digit for each row.
The inner loop repeats that digit exactly i times.
Total digits printed follow a triangular count: n(n+1)/2.
Changing what you print (i vs j) creates many new patterns with the same loop skeleton.
❓ Frequently Asked Questions
i inside the inner loop. Since i stays constant for that row, you get repeated digits like 55555 and 4444.for (i = 1; i <= rows; i++). Keep the inner loop as for (j = 1; j <= i; j++).cout << i << ' ';. This improves readability, especially for larger patterns.Explore More C++ Number Patterns!
Keep practicing nested loops with more patterns and variations.
Even though the digits change each row, the total number of printed characters is still triangular: n(n+1)/2 for n rows.
12 people found this page helpful
