Centered Increasing Number Triangle in C++

What You’ll Learn
How to print a centered triangle of increasing numbers in C++:
1, 2 3 4, 5 6 7 8 9
We print leading spaces for centering and keep a counter to continue numbers across rows.
⭐ Pattern Output
For the example shown, the output looks like this:
1
2 3 4
5 6 7 8 9Complete C++ Program
The outer loop controls row width (1, 3, 5). The inner loop prints spaces on the left and then consecutive numbers using k++.
#include <iostream>
using namespace std;
int main() {
int i, j;
int k = 1;
int rowsWidth = 5;
for (i = 1; i <= rowsWidth; i += 2) {
for (j = rowsWidth; j >= 1; j--) {
if (j > i) cout << " ";
else cout << k++ << " ";
}
cout << "\n";
}
return 0;
}🧠 How It Works
Initialize the counter
int k = 1; ensures the numbers keep increasing across rows.
Pick odd row widths
for (i = 1; i <= 5; i += 2) creates row widths 1, 3, and 5.
Print spaces then numbers
When j > i, we print a space to push output right. Otherwise we print k++ followed by a space.
Centered consecutive triangle
This approach prints a centered triangle while keeping the sequence continuous.
Variation — User Input Version
Let the user choose the bottom width (odd number). The triangle will be centered automatically.
#include <iostream>
using namespace std;
int main() {
int width;
int i, j;
int k = 1;
cout << "Enter the bottom width (odd number): ";
cin >> width;
if (!cin || width <= 0) return 0;
if (width % 2 == 0) width--; // make it odd
if (width <= 0) return 0;
for (i = 1; i <= width; i += 2) {
for (j = width; j >= 1; j--) {
if (j > i) cout << " ";
else cout << k++ << " ";
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Use
setw(2)orsetw(3)(from<iomanip>) to keep alignment after 9 - Remove trailing spaces by printing a space only between values
- Start the counter from another value (e.g.,
k = 10) to shift the sequence - Print a full pyramid by continuing past the middle and then decreasing widths
- Replace numbers with characters to build centered alphabet patterns
Avoid
- Using even widths (convert to odd so centering stays symmetric)
- Using
endlin loops (unnecessary flushing) - Not validating
cininput before usingwidth - Forgetting the counter needs to stay outside the outer loop
Key Takeaways
Odd widths (1, 3, 5, ...) make it easy to center the triangle.
Leading spaces shift the numbers right to create centering.
A counter k keeps the number sequence continuous across rows.
This pattern can be extended into a full pyramid by adding decreasing widths.
❓ Frequently Asked Questions
k is not reset inside the outer loop. It keeps incrementing as you print.<iomanip> and print with setw(2) or setw(3) so all numbers use the same width.Explore More C++ Number Patterns!
Centered triangles are great practice for combining spacing logic with counters.
Many centered patterns work by printing spaces first and then the pattern content. Getting the spacing right is often the hardest part.
12 people found this page helpful
