Left Half Pyramid in C++
Print a left half pyramid in C++ by printing rows - i padding spaces before i stars on each line. Shows why the padding is two spaces wide to match "* ".
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}
Sample Output
*
Row 1: four two-space pads, then one star.
* * * * *
Row 5: no padding.
In this one
- How a padding loop shifts a pattern to the right
- Why the pad width must match the star width
- How rows - i shrinks as i grows
- The order of the two inner loops
How it works
- 1
Read rows (5).
- 2
For each row i, print rows - i pads of two spaces.
- 3
Then print i copies of "* ".
- 4
End the line with endl.
Edge cases
Single space pad
Change " " to " ".
The right edge stops lining up because each star takes two characters, so the triangle leans.
rows = 1
Enter 1.
Zero pads and one star: just *.
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:
Print spaces before stars. Stars first and you get the right-half again.
rows - i going negative never happens here because i ≤ rows.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
On row 2 of 5 rows, how many pad units print?
Pick an answer to check it.
Question 2
What happens if stars print before spaces?
Pick an answer to check it.
Questions people ask
Why two loops inside the outer loop?
One prints the spacing, the other prints the stars. Each has its own count.
How do I make it upside down?
Run i from rows down to 1 with the same inner loops.
Why do some consoles show it crooked?
A proportional font makes spaces narrower than stars. Use a monospaced font.