Star Pattern in C++

Three star pyramids in one C++ file: right-half, left-half, full. Same loops as the beginner pattern pages.

IntermediateAdvanced Pattern ProgramsExample 1 of 6
star-pattern.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 // Right Half Pyramid
11 cout << "\nRight Half Pyramid:" << endl;
12 for (int i = 1; i <= rows; i++) {
13 for (int j = 1; j <= i; j++) {
14 cout << "* ";
15 }
16 cout << endl;
17 }
18
19 // Left Half Pyramid
20 cout << "\nLeft Half Pyramid:" << endl;
21 for (int i = 1; i <= rows; i++) {
22 for (int j = 1; j <= rows - i; j++) {
23 cout << " ";
24 }
25 for (int j = 1; j <= i; j++) {
26 cout << "* ";
27 }
28 cout << endl;
29 }
30
31 // Full Pyramid
32 cout << "\nFull Pyramid:" << endl;
33 for (int i = 1; i <= rows; i++) {
34 for (int j = 1; j <= rows - i; j++) {
35 cout << " ";
36 }
37 for (int j = 1; j <= 2 * i - 1; j++) {
38 cout << "*";
39 }
40 cout << endl;
41 }
42
43 return 0;
44}

Output

Enter number of rows: 5

Right Half Pyramid:
*
* *
* * *
* * * *
* * * * *

Left Half Pyramid:
        *
      * *
    * * *
  * * * *
* * * * *

Full Pyramid:
    *
   ***
  *****
 *******
*********

What's going on

One file, three pyramids you already know from Pattern Programs. rows = 5 in the sample.

Right-half: inner j <= i, "* ". Row i has i stars.

Left-half: pad (rows - i) times with " ", then the same stars. Two spaces per pad so they match "* ".

Full: pad rows - i with " ", then 2 * i - 1 times "*". Odd counts: 1, 3, 5, 7, 9. No space between stars.

Each block prints a label, then endl after the inner loops. Same bugs as the single-pattern pages: < rows drops the last row, " " vs " " leans the left-half.

This page is a cheat sheet. The deep walk is on Right Half / Left Half / Full Pyramid.