Increasing Shifted Number Triangle in C++

What You’ll Learn
How to print an increasing shifted number triangle in C++ where each row begins with the row number and continues sequentially.
The key idea is to print i + j - 1 while the inner loop runs from 1 to i.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9Complete C++ Program
Fixed five rows: the inner loop prints i values, and the expression i + j - 1 generates consecutive numbers on each row.
#include <iostream>
using namespace std;
int main() {
int rows = 5;
int i, j;
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
if (j > 1) cout << ' ';
cout << (i + j - 1);
}
cout << "\n";
}
return 0;
}🧠 How It Works
Choose the row count
int rows = 5; sets how many lines the triangle prints.
Outer loop (rows)
for (i = 1; i <= rows; i++) controls the current row number i.
Inner loop (print i values)
for (j = 1; j <= i; j++) prints exactly i numbers on row i.
Compute the value
Printing i + j - 1 makes each row start at i and increase by 1 as j grows.
Shifted consecutive numbers
Total printed numbers are 1+2+…+n = n(n+1)/2, so time complexity is O(n²) for n rows.
Variation — User Input Version
Let the user decide the number of rows 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 = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
if (j > 1) cout << ' ';
cout << (i + j - 1);
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Validate input (e.g., check
cin.fail()) before usingrows - Right-align the triangle by printing leading spaces before each row
- Start each row from a different base (e.g.,
base + i + j - 1) - Format with fixed width using
setw()for neat columns - Try the decreasing-width version by printing
j = 1..(rows-i+1)
Avoid
- Hard-coding
5in multiple places (userows) - Printing extra spaces at the end of each line (use a separator rule)
- Forgetting the newline after each row
- Using
endlinside loops (it flushes output and slows printing)
Key Takeaways
The outer loop selects the row number i.
The inner loop prints exactly i numbers on row i.
The expression i + j - 1 creates the shifted consecutive sequence per row.
Work is triangular: n(n+1)/2, which gives O(n²) time.
❓ Frequently Asked Questions
i prints i + 1 - 1 first, which equals i. So row 1 starts at 1, row 2 starts at 2, row 3 starts at 3, and so on.base + i + j - 1. If base = 10, the first row starts at 11 instead of 1.if (j > 1) cout << ' '; line.Explore More C++ Number Patterns!
Keep practicing nested loops by building triangles, pyramids, and shifting sequences.
The formula i + j - 1 is a classic way to build diagonals of consecutive numbers in grids and triangles. It shows up often in pattern problems because it naturally increases by 1 as you move right.
12 people found this page helpful
