Full Pyramid in C++
Print a centered full pyramid of stars in C++ using rows - i spaces and 2i - 1 stars per row. Explains where the odd numbers come from and how to center it.
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 <= 2 * i - 1; j++) {17 cout << "*";18 }19 cout << endl;20 }2122 return 0;23}
Sample Output
*
Row 1: 4 spaces, 1 star.
*********
Row 5: 0 spaces, 9 stars.
In this one
- Why row i of a centered pyramid has 2i - 1 stars
- How single-space padding centers stars printed with no gap
- How two inner loops build one row
- How the bottom row width relates to rows
How it works
- 1
Read rows (5).
- 2
Row i prints rows - i single spaces.
- 3
Then it prints 2i - 1 stars: 1, 3, 5, 7, 9.
- 4
endl ends each row.
Edge cases
Using i stars
Replace 2 * i - 1 with i.
Rows get 1, 2, 3 stars and the pyramid loses its center, because even counts cannot sit evenly under one top star.
Very large rows
Enter 60.
The base is 119 characters wide and may wrap in a narrow terminal, breaking the shape visually.
What's going on
A centered triangle: odd star counts 1, 3, 5, 7, 9. Row i has rows - i single spaces, then 2 * i - 1 stars with no extra space between them.
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= rows - i; j++) cout << " ";
One space. Not " ". The stars are "*" not "* ", so the pad is half as wide.
for (int j = 1; j <= 2 * i - 1; j++) cout << "*";
Walk 5:
2 * i - 1 is 1, 3, 5, 7, 9. Use i here and you reprint the right-half, just centered a bit.
Inverted pyramid is this loop running i from rows down to 1.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
How many stars are on row 6?
Pick an answer to check it.
Question 2
Why is the pad one space here but two in the left half pyramid?
Pick an answer to check it.
Questions people ask
Why 2i - 1?
Each new row adds one star on each side, so the count grows by 2 starting from 1: 1, 3, 5 ...
How wide is the base?
2 × rows − 1 characters.
How do I make it hollow?
Print a star only at the first and last positions and on the last row. See Pyramid Program.