Inverted Pyramid in C++
Inverted star pyramid in C++. Count i down from rows. Same 2*i-1 stars as the full pyramid.
IntermediatePattern ProgramsExample 4 of 6
inverted-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 = 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}
Output
Enter number of rows: 5
*********
*******
*****
***
*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=5: 0 spaces, 9 stars
i=4: 1 space, 7 stars
i=3: 2 spaces, 5 stars
i=2: 3 spaces, 3 stars
i=1: 4 spaces, 1 star
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.