Right-Aligned Number Triangle in C++

What You’ll Learn
How to print a right-aligned triangle where row i prints the sequence 1..i.
This pattern is a neat way to practice:
- Using one loop to print leading spaces
- Using another loop to print increasing numbers
- Formatting columns with
setw()
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5Complete C++ Program
First print spaces to align the row, then print numbers 1 to i using setw(2).
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int i, j, k;
for (i = 1; i <= 5; i++) {
for (j = 5; j > i; j--)
cout << " ";
for (k = 1; k <= i; k++)
cout << setw(2) << k;
cout << "\n";
}
return 0;
}🧠 How It Works
Choose the size
We print 5 rows in this example (i = 1..5).
Print leading spaces
The first inner loop prints spaces while j > i. That makes the first rows shift to the right.
Print numbers 1..i
The second inner loop prints k from 1 to i, producing rows like 1 2 3.
Format with setw(2)
setw(2) keeps spacing consistent between numbers.
Right-aligned triangle
Total printed numbers are 1+2+…+n, so runtime is O(n²) for n rows.
Variation — User Input Version
Let the user choose the number of rows at runtime.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int rows;
cout << "Enter the number of rows: ";
cin >> rows;
if (rows <= 0) return 0;
for (int i = 1; i <= rows; i++) {
for (int j = rows; j > i; j--)
cout << " ";
for (int k = 1; k <= i; k++)
cout << setw(2) << k;
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Print
i..1to create a decreasing number triangle - Use a different alignment by changing the space loop
- Increase
setw()if you print numbers above 9 - Replace numbers with letters to make an alphabet version
- Validate input using
cin.fail()when taking user input
Avoid
- Mixing tabs and spaces (alignment may break)
- Forgetting the newline after each row
- Hard-coding the row count when you want a reusable solution
- Using
endlin tight loops (extra flushing)
Key Takeaways
Row i prints the sequence 1..i.
Leading spaces right-align the triangle.
setw(2) improves column alignment.
Total prints are n(n+1)/2, giving O(n²) time.
❓ Frequently Asked Questions
1..i on each row.iomanip provides setw(), which helps format and align numbers in neat columns.Explore More C++ Number Patterns!
Once you can control spaces and loop bounds, you can align patterns in many different ways.
If you replace the leading spaces with leading zeros or dots, you can “see” the alignment logic more clearly while debugging pattern programs.
12 people found this page helpful
