Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

IntermediatePattern ProgramsExample 4 of 6
inverted-pyramid.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int rows;
6
7 cout << "Enter number of rows: ";
8 cin >> rows;
9
10 for (int i = rows; i >= 1; i--) {
11 // Print spaces
12 for (int j = 1; j <= rows - i; j++) {
13 cout << " ";
14 }
15 // Print stars
16 for (int j = 1; j <= 2 * i - 1; j++) {
17 cout << "*";
18 }
19 cout << endl;
20 }
21
22 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. 1

    Read rows (5).

  2. 2

    i starts at 5 and decreases to 1.

  3. 3

    Print rows - i spaces (0 at first).

  4. 4

    Print 2i - 1 stars (9 at first).

  5. 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=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.

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.