Continuous Number Triangle in C++

What You’ll Learn
How to print a triangle of consecutive integers in C++:
1, 2 3, 4 5 6, 7 8 9 10
We use a counter variable that increments after each print, so numbers continue across rows.
⭐ Pattern Output
For rows = 4, the pattern looks like this:
1
2 3
4 5 6
7 8 9 10Complete C++ Program
The outer loop controls rows. The inner loop prints values using k++, which increments after each print.
#include <iostream>
using namespace std;
int main() {
int rows = 4;
int i, j;
int k = 1;
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
cout << k++ << " ";
}
cout << "\n";
}
return 0;
}🧠 How It Works
Initialize the counter
int k = 1; starts the sequence at 1.
Outer loop (rows)
for (i = 1; i <= rows; i++) makes row 1 print 1 number, row 2 print 2 numbers, and so on.
Inner loop (print and increment)
cout << k++; prints the current value and increments it for the next position.
New line
cout << "\\n"; moves to the next row after printing each line.
Continuous sequence triangle
Because k is not reset per row, the sequence continues from one line to the next.
Variation — User Input Version
Let the user choose the number of rows at runtime.
#include <iostream>
using namespace std;
int main() {
int rows;
int i, j;
int k = 1;
cout << "Enter the number of rows: ";
cin >> rows;
if (!cin || rows <= 0) return 0;
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
cout << k++ << " ";
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Remove trailing spaces by printing a space only between values
- Start from a different number (e.g.,
k = 10) to shift the sequence - Format output with fixed width for aligned columns
- Print the triangle in reverse by looping i downwards
- Use the same idea to build multiplication or square tables
Avoid
- Resetting
kinside the loop (you’ll lose the continuous sequence) - Using
endlin tight loops (unnecessary flushing) - Not validating input (negative/zero rows)
- Mixing row and column variables in the inner loop
Key Takeaways
A counter variable (k) carries the sequence across rows.
The outer loop controls how many numbers print per row.
The total printed numbers are \(n(n+1)/2\) for \(n\) rows.
This pattern is a close relative of Floyd’s triangle.
❓ Frequently Asked Questions
k is declared outside the outer loop and incremented after each print.Explore More C++ Number Patterns!
Continuous-number triangles are a classic way to practice nested loops and counters.
The total count of printed numbers in a triangle is a triangular number: \(1+2+\dots+n = n(n+1)/2\).
12 people found this page helpful
