Pyramid Program in C++
Print a full, an inverted, and a hollow centered pyramid in C++. The hollow one tests the first star, the last star, and the base row in one condition.
1#include <iostream>2using namespace std;34int main() {5 int rows;67 cout << "Enter number of rows: ";8 cin >> rows;910 // Full Pyramid11 cout << "\nFull Pyramid:" << endl;12 for (int i = 1; i <= rows; i++) {13 for (int j = 1; j <= rows - i; j++) {14 cout << " ";15 }16 for (int j = 1; j <= 2 * i - 1; j++) {17 cout << "*";18 }19 cout << endl;20 }2122 // Inverted Pyramid23 cout << "\nInverted Pyramid:" << endl;24 for (int i = rows; i >= 1; i--) {25 for (int j = 1; j <= rows - i; j++) {26 cout << " ";27 }28 for (int j = 1; j <= 2 * i - 1; j++) {29 cout << "*";30 }31 cout << endl;32 }3334 // Hollow Pyramid35 cout << "\nHollow Pyramid:" << endl;36 for (int i = 1; i <= rows; i++) {37 for (int j = 1; j <= rows - i; j++) {38 cout << " ";39 }40 for (int j = 1; j <= 2 * i - 1; j++) {41 if (j == 1 || j == 2 * i - 1 || i == rows) {42 cout << "*";43 } else {44 cout << " ";45 }46 }47 cout << endl;48 }4950 return 0;51}
Sample Output
* *
Hollow row 3: two edges and a three-space interior.
*********
Hollow base row.
In this one
- How full and inverted pyramids share inner loops
- How to place stars only on the outline of a centered shape
- Why the gap here is one space
- Which positions count as edges in a 2i - 1 row
How it works
- 1
Read rows (5).
- 2
Full: spaces rows - i, stars 2i - 1.
- 3
Inverted: same, with i counting down.
- 4
Hollow: star if j == 1, j == 2i - 1, or i == rows; else a space.
Edge cases
Wrong gap width
Use " " for the gap.
Interior rows become too wide and the outline breaks, because stars here are one character.
rows = 1
Enter 1.
All three blocks print one star.
What's going on
Three centered pyramids: full, inverted, hollow. Same 2 * i - 1 star count as Full Pyramid.
Full: i = 1..rows, pad rows - i with " ", then that many "*".
Inverted: i = rows..1, same inners. 9 stars first when rows is 5.
Hollow:
if (j == 1 || j == 2 * i - 1 || i == rows) cout << "*"; else cout << " ";
Left peak, right peak, and the entire base. Interior is a single space — stars here have no trailing space, so the gap is " ", not " ".
Walk 5, hollow:
i == rows missing → the base is two corners. 2 * i without - 1 → even counts and it stops looking like a triangle.
Labels between blocks so the three dumps don't run together.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
On row 3 of the hollow pyramid, which j values print a star?
Pick an answer to check it.
Question 2
What closes the bottom of the hollow pyramid?
Pick an answer to check it.
Questions people ask
Why is j == 2 * i - 1 the right edge?
Row i has 2i − 1 stars, so the last position is 2i − 1.
Is this the same as the triangle page?
The idea is the same, but this one is centered with odd row lengths.
How do I make a hollow inverted pyramid?
Apply the same condition inside the inverted loop.