Full Pyramid in C++

Centered star pyramid in C++. Row i: rows-i spaces, then 2*i-1 stars.

IntermediatePattern ProgramsExample 3 of 6
full-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 = 1; i <= rows; 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}

Output

Enter number of rows: 5
    *
   ***
  *****
 *******
*********

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:

i=1: 4 spaces, 1 star
i=2: 3 spaces, 3 stars
i=3: 2 spaces, 5 stars
i=4: 1 space, 7 stars
i=5: 0 spaces, 9 stars

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.