Inverted Pyramid in C++
Print an inverted centered pyramid in C++ by running the outer loop from rows down to 1. Same star and space formulas as the full pyramid, read in reverse.
1#include <iostream>2using namespace std;34int main() {5 int rows;67 cout << "Enter number of rows: ";8 cin >> rows;910 for (int i = rows; i >= 1; i--) {11 // Print spaces12 for (int j = 1; j <= rows - i; j++) {13 cout << " ";14 }15 // Print stars16 for (int j = 1; j <= 2 * i - 1; j++) {17 cout << "*";18 }19 cout << endl;20 }2122 return 0;23}
Sample Output
*********
i = 5: widest row.
*
i = 1: the point at the bottom.
In this one
- How a counting-down loop works (i--)
- How reversing the outer loop flips a pattern
- Why the inner formulas need no change
- Which off-by-one mistakes add or lose a row
How it works
- 1
Read rows (5).
- 2
i starts at 5 and decreases to 1.
- 3
Print rows - i spaces (0 at first).
- 4
Print 2i - 1 stars (9 at first).
- 5
End each line.
Edge cases
Condition i >= 0
Change i >= 1 to i >= 0.
A row with i = 0 prints 5 spaces and 2×0−1 = −1 stars, so an empty extra line appears.
i++ instead of i--
Start at rows and increase.
i keeps growing past rows, the condition i >= 1 stays true, and the loop runs until int overflows. Effectively an infinite loop.
What's going on
Full pyramid upside down. Start wide, get narrow. Outer loop counts down.
for (int i = rows; i >= 1; i--)
i = 5, 4, 3, 2, 1 when rows is 5.
Spaces: j <= rows - i. When i is 5 that's 0 spaces. When i is 1 that's 4 spaces. The peak of the inverted triangle is the last line.
Stars: j <= 2 * i - 1, "*". Same odd counts, reverse order: 9, 7, 5, 3, 1.
Walk 5:
i++ instead of i-- and you reprint the full pyramid. i >= 0 adds a garbage row.
This is the full-pyramid inner loops with a countdown outer loop. Don't rewrite the star formula.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
First row stars for rows = 4?
Pick an answer to check it.
Question 2
Which header makes the loop count down?
Pick an answer to check it.
Questions people ask
Can I reuse the full pyramid code?
Yes. Only the outer loop header changes.
What is the last row?
A single star with rows − 1 spaces in front.
How do I build a diamond?
Print a full pyramid, then this inverted one starting from rows − 1.