Right Half Pyramid in C++

Right-half star pyramid in C++: row i prints i stars. Nested loops. rows=5 → 1..5 stars.

BeginnerPattern ProgramsExample 1 of 6
right-half-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 for (int j = 1; j <= i; j++) {
12 cout << "* ";
13 }
14 cout << endl;
15 }
16
17 return 0;
18}

Output

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

What's going on

A right-half pyramid is row i printing i stars. Nested loops: outer is the row, inner is how many stars. For 5 rows you get 1, then 2, then 3, then 4, then 5.

cin >> rows;

Sample: 5.

for (int i = 1; i <= rows; i++)

One pass per line.

for (int j = 1; j <= i; j++)

cout << "* ";

The inner limit is i, not rows. That's why row 1 has one star and row 5 has five.

cout << endl;

After the inner loop. Forget it and all the stars sit on one line.

Walk 5:

i=1: one *
i=2: * *
i=3: * * *
i=4: * * * *
i=5: * * * * *

* includes a trailing space. Looks fine. cout << "*" with no space glues them into one blob.

Left-half is this plus a space loop first. Full pyramid is odd counts and a single-space pad.