Incremental Number Pattern in C++

What You’ll Learn
How to print a triangle pattern where each row starts with the row number and the remaining values are built by adding a decreasing step:
1, 2 6, 3 7 10, 4 8 11 13, 5 9 12 14 15.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15Complete C++ Program
Start each row with res = i, then repeatedly add a decreasing value k to generate the next outputs in that row.
#include <iostream>
using namespace std;
int main() {
int i, j, k, res;
for (i = 1; i <= 5; i++) {
k = 4;
res = i;
for (j = i; j < i + i; j++) {
if (i == j)
cout << j << " ";
else {
res = res + k;
cout << res << " ";
k--;
}
}
cout << "\n";
}
return 0;
}🧠 How It Works
Choose the row
The outer loop runs i = 1..rows. Each i prints one row.
Initialize res and step
Set res = i (first number of the row) and k = rows - 1 (starting step).
Print the first value directly
When j == i, the program prints j (which equals the row number).
Build remaining values
On each next iteration, add the current k to res and then decrement k. This produces a decreasing step sequence within the row.
A stepped triangle
Each row uses a decreasing increment so later values grow, but by smaller and smaller jumps.
Variation — User Input Version
Let the user choose rows. This keeps the same logic for any positive number of 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++) {
int k = rows - 1;
int res = i;
for (int j = i; j < i + i; j++) {
if (i == j) cout << j << " ";
else {
res += k;
cout << res << " ";
k--;
}
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Remove trailing spaces by printing spaces conditionally (or build a row string)
- Print a centered version by adding leading spaces before each row
- Try printing the same pattern with commas to visualize the sequence
- Derive the numbers mathematically and compare with the loop output
- Use
long longif you try large row counts
Avoid
- Forgetting to reset
kandresat the start of each row - Using
endlin loops (extra flushing) - Letting
kgo negative by running too many iterations in a row - Hard-coding
5if you want a flexible program
Key Takeaways
Each row begins with the row index i.
A running res value generates the next numbers in the row.
The step k decreases within the row, changing the jump size.
Total printed values are \(1+2+\dots+n\), so runtime is about O(n²).
❓ Frequently Asked Questions
i once before the loop and then run a smaller loop for the remaining values.rows-1.Explore More C++ Number Patterns!
Patterns like this are great for practicing loops plus state updates inside the loop.
If you rewrite the code to print i first and then loop only i-1 times for the rest, the logic becomes clearer and you can remove the i == j special case.
12 people found this page helpful
