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;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}
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.