Ascending Number Triangle in C++

What You’ll Learn
How to print the ascending number triangle pattern 1, 12, 123, 1234, 12345 in C++ using nested for loops.
The outer loop controls the number of rows, and the inner loop prints 1..i on each row.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
12
123
1234
12345Complete C++ Program
Fixed five rows: the inner loop prints from 1 up to the current row number i.
#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++) {
cout << j;
}
cout << "\n";
}
return 0;
}🧠 How It Works
Choose the row count
int rows = 5; sets the height of the triangle.
Outer loop (rows)
for (i = 1; i <= rows; i++) runs one iteration per row. Row i prints i numbers.
Inner loop (print 1..i)
for (j = 1; j <= i; j++) prints 1 to i using cout << j.
New line
cout << "\n"; moves to the next row after each line.
Ascending number triangle
Total numbers printed: 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++) {
cout << j;
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Validate input (e.g., check
cin.fail()) before usingrows - Add spaces between numbers with
cout << j << ' ' - Print an inverted triangle by counting the outer loop down
- Try printing repeated digits (
11111,2222, ...) by printingiinstead ofj - Right-align the triangle by printing leading spaces before each row
Avoid
- Forgetting to print a newline between rows
- Using negative or zero rows without validating input
- Mixing row/column logic (keep the outer loop for rows)
- Flushing output with
endlunnecessarily in tight loops
Key Takeaways
The outer loop controls rows; row i prints exactly i numbers.
The inner loop prints the range 1..i, producing the growing triangle.
Total printed digits follow the triangular number count: n(n+1)/2.
This is a foundational pattern for many others (stars, alphabets, Floyd’s triangle, and more).
❓ Frequently Asked Questions
i, the inner loop runs from 1 to i. That prints 1 number on row 1, 2 numbers on row 2, and so on.cout << j << ' ';. You can also avoid the trailing space with a small conditional.for (i = rows; i >= 1; i--) and keep the inner loop as for (j = 1; j <= i; j++).Explore More C++ Number Patterns!
Keep going to learn more number patterns and loop tricks.
This pattern is one of the first stepping stones toward Floyd’s triangle and other triangular number patterns.
12 people found this page helpful
