Triangle Pattern in C++
Print a right triangle, an inverted triangle, and a hollow triangle in C++. Learn how one if condition places stars only on the edges and the bottom row.
1#include <iostream>2using namespace std;34int main() {5 int rows;67 cout << "Enter number of rows: ";8 cin >> rows;910 // Right Triangle11 cout << "\nRight Triangle:" << endl;12 for (int i = 1; i <= rows; i++) {13 for (int j = 1; j <= i; j++) {14 cout << "* ";15 }16 cout << endl;17 }1819 // Inverted Right Triangle20 cout << "\nInverted Right Triangle:" << endl;21 for (int i = rows; i >= 1; i--) {22 for (int j = 1; j <= i; j++) {23 cout << "* ";24 }25 cout << endl;26 }2728 // Hollow Triangle29 cout << "\nHollow Triangle:" << endl;30 for (int i = 1; i <= rows; i++) {31 for (int j = 1; j <= i; j++) {32 if (j == 1 || j == i || i == rows) {33 cout << "* ";34 } else {35 cout << " ";36 }37 }38 cout << endl;39 }4041 return 0;42}
Sample Output
* *
Hollow row 3: two edge stars with a two-space gap.
* * * * *
Hollow last row: filled.
In this one
- How a decreasing outer loop inverts a triangle
- How to print only the border of a shape
- Why the gap must be two spaces to match "* "
- How j == 1, j == i, and i == rows describe the edges
How it works
- 1
Read rows (5).
- 2
Right triangle: i stars on row i.
- 3
Inverted: i goes from rows down to 1.
- 4
Hollow: print "* " when j == 1, j == i, or i == rows, else two spaces.
Hollow triangle, rows = 5
Which cells get a star.
- 1.Row 1: j=1 → *
- 2.Row 3: j=1 *, j=2 gap, j=3 *
- 3.Row 5: last row, all five stars
Edge cases
Missing i == rows
Remove the last-row condition.
The bottom row becomes two corner stars with a gap in between, leaving the triangle open.
rows = 2
Enter 2.
Row 2 has only j = 1 and j = 2, both edges, so the hollow triangle looks the same as the solid one.
What's going on
Three triangles in one run. Right, inverted, hollow. Sample rows = 5.
Right triangle is the right-half pyramid: j <= i, "* ".
Inverted: outer i counts down rows to 1. Inner still j <= i. First line five stars, last line one. i++ instead of i-- reprints the right triangle.
Hollow is the new bit:
if (j == 1 || j == i || i == rows) cout << "* "; else cout << " ";
Star on the left edge (j == 1), the right edge (j == i), and the whole last row. Inside: two spaces so the column still lines up with "* ".
Walk 5, hollow:
Use " " for the gap and the hollow leans. Skip i == rows and the base is two corners with a hole.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
On row 4 of the hollow triangle, which j values print a star?
Pick an answer to check it.
Question 2
What changes to turn the right triangle into the inverted one?
Pick an answer to check it.
Questions people ask
Why test i == rows?
It fills the bottom row completely, closing the shape.
Can I make a hollow square?
Yes: print a star when the row or column is first or last.
Why two spaces for the gap?
Each star prints as "* ", so a gap must also take two characters.