Decreasing Length Sequential Number Pattern in C++

What You’ll Learn
How to print a decreasing-length triangle of consecutive integers in C++.
The first row prints 5 numbers, the next prints 4, then 3, then 2, then 1—resulting in values from 1 to 15.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1 2 3 4 5
6 7 8 9
10 11 12
13 14
15Complete C++ Program
A counter k prints consecutive numbers. The inner loop length shrinks each row.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int rows = 5;
int i, j;
int k = 1;
for (i = 1; i <= rows; i++) {
for (j = rows; j >= i; j--) {
cout << setw(3) << k++;
}
cout << "\n";
}
return 0;
}🧠 How It Works
Initialize the counter
k = 1 is the next number to print.
Outer loop controls rows
for (i = 1; i <= rows; i++) prints one line per iteration.
Inner loop shrinks each row
for (j = rows; j >= i; j--) runs rows - i + 1 times, so the row length decreases by 1 each line.
setw(3) formats output
setw(3) reserves 3 characters so values align as columns.
Decreasing sequential triangle
Total printed numbers are n(n+1)/2, so work is O(n²) for n rows.
Variation — User Input Version
Let the user choose the number of rows using cin:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int rows;
int i, j;
int k = 1;
cout << "Enter the number of rows: ";
cin >> rows;
for (i = 1; i <= rows; i++) {
for (j = rows; j >= i; j--) {
cout << setw(3) << k++;
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Increase the
setw()width for larger outputs (e.g.,setw(4)) - Start from a different initial number (set
kto something else) - Print the increasing-length version by changing the inner loop bounds
- Center-align the triangle by adding leading spaces per row
- Replace numbers with characters to create alphabet triangles
Avoid
- Forgetting to include
<iomanip>when usingsetw() - Using
endlinside loops (it flushes output and slows printing) - Hard-coding the row count everywhere (store it in one variable)
- Reinitializing
kinside the outer loop (that would restart numbering each row)
Key Takeaways
A counter k prints consecutive integers across all rows.
The inner loop length is rows - i + 1, so each row is shorter.
setw(3) ensures aligned columns for neat output.
Total printed numbers follow n(n+1)/2, so time is O(n²).
❓ Frequently Asked Questions
j >= i. When i increases, the loop runs one fewer time.int k = 1; inside the outer loop. That will print 1..rowLength on every row instead of continuing the sequence.setw(4) or more depending on the maximum value you plan to print.Explore More C++ Number Patterns!
Try varying the inner loop bounds to create shrinking, growing, or centered number triangles.
Patterns that count sequentially across rows often use a single counter like k. That one variable can turn many loop shapes into interesting number designs.
12 people found this page helpful
