Triangle Pattern in C++

Right, inverted, and hollow triangles in C++. Hollow: star on j==1, j==i, and the last row.

IntermediateAdvanced Pattern ProgramsExample 2 of 6
triangle-pattern.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int rows;
6
7 cout << "Enter number of rows: ";
8 cin >> rows;
9
10 // Right Triangle
11 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 }
18
19 // Inverted Right Triangle
20 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 }
27
28 // Hollow Triangle
29 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 }
40
41 return 0;
42}

Output

Enter number of rows: 5

Right Triangle:
*
* *
* * *
* * * *
* * * * *

Inverted Right Triangle:
* * * * *
* * * *
* * *
* *
*

Hollow Triangle:
*
* *
*   *
*     *
* * * * *

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:

row 1: one cell, always a star
row 2: star star (both edges)
row 3: star, gap, star
row 4: star, gap, gap, star
row 5: five stars

Use " " for the gap and the hollow leans. Skip i == rows and the base is two corners with a hole.