Increasing Sum Number Triangle (0-Based) in C++

What You’ll Learn
How to print an increasing sum triangle in C++ that starts from 0 and grows row by row.
The idea is simple: for each cell, print i + j where i is the current row index and j is the column index.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
0
1 2
2 3 4
3 4 5 6
4 5 6 7 8
5 6 7 8 9 10Complete C++ Program
This version prints 6 lines (from i = 0 to 5). Each line prints values computed as i + j.
#include <iostream>
using namespace std;
int main() {
int maxRow = 5;
int i, j;
for (i = 0; i <= maxRow; i++) {
for (j = 0; j <= i; j++) {
if (j > 0) cout << ' ';
cout << (i + j);
}
cout << "\n";
}
return 0;
}🧠 How It Works
Set the last row index
int maxRow = 5; prints rows from 0 through 5 (total 6 lines).
Outer loop (0-based rows)
for (i = 0; i <= maxRow; i++) controls which row is being printed.
Inner loop (0..i values)
for (j = 0; j <= i; j++) prints exactly i + 1 values on row i.
Compute the sum
Printing i + j makes each row start at i and increase by 1 as j increases.
Sum-based triangle
Total printed values are triangular (6 rows here): 1+2+…+n, so time complexity is O(n²).
Variation — User Input Version
Let the user decide the last row index (maximum row value) using cin:
#include <iostream>
using namespace std;
int main() {
int maxRow;
int i, j;
cout << "Enter the last row index (e.g., 5): ";
cin >> maxRow;
for (i = 0; i <= maxRow; i++) {
for (j = 0; j <= i; j++) {
if (j > 0) cout << ' ';
cout << (i + j);
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Change the value rule to create new patterns (e.g.,
i*j,i-j, ori*i + j) - Format numbers with fixed width using
setw()for alignment - Convert to 1-based output by printing
i + j + 1instead - Make it right-aligned by printing leading spaces before each row
- Print only even sums by checking
(i+j)%2==0
Avoid
- Hard-coding the size in multiple places (store it in one variable)
- Printing trailing spaces if exact formatting matters (use a separator rule)
- Forgetting the newline after each row
- Using
endlinside loops (it flushes output and slows printing)
Key Takeaways
Starting the loops from 0 makes the first printed value 0.
The number of values on row i is i+1 because j runs from 0 to i.
The value rule i + j increases by 1 as you move right.
Total work is quadratic in the number of rows: O(n²).
❓ Frequently Asked Questions
i = 0, and the inner loop runs only once with j = 0. The value is i + j = 0.i + j + 1 instead of i + j. The output becomes 1, 2 3, 3 4 5, ...rows lines, loop i from 0 to rows-1. That prints 1 line when rows=1, 2 lines when rows=2, etc.Explore More C++ Number Patterns!
Try changing the value rule to create dozens of pattern variations with the same loop structure.
The formula i + j creates constant-sum diagonals in a 2D grid. That’s why it naturally forms neat increasing sequences in triangles and matrices.
12 people found this page helpful
