Left Half Pyramid in C++
Left-half (right-aligned) pyramid in C++. Print (rows-i) space-pairs, then i stars.
BeginnerPattern ProgramsExample 2 of 6
left-half-pyramid.cpp
1#include <iostream>2using namespace std;34int main() {5 int rows;67 cout << "Enter number of rows: ";8 cin >> rows;910 for (int i = 1; i <= rows; i++) {11 // Print spaces12 for (int j = 1; j <= rows - i; j++) {13 cout << " ";14 }15 // Print stars16 for (int j = 1; j <= i; j++) {17 cout << "* ";18 }19 cout << endl;20 }2122 return 0;23}
Output
Enter number of rows: 5
*
* *
* * *
* * * *
* * * * *What's going on
Same star counts as the right-half pyramid, shoved right with spaces. Row i: (rows − i) space-pairs, then i stars.
for (int i = 1; i <= rows; i++)
Spaces first:
for (int j = 1; j <= rows - i; j++)
cout << " ";
Two spaces per pad so they line up with "* " (star plus space). One space and the triangle leans.
Then the same star loop as right-half: j from 1 to i, "* ".
Walk 5:
i=1: 4 pads, 1 star
i=2: 3 pads, 2 stars
i=3: 2 pads, 3 stars
i=4: 1 pad, 4 stars
i=5: 0 pads, 5 stars — flush left
Print spaces before stars. Stars first and you get the right-half again.
rows - i going negative never happens here because i ≤ rows.