Star Pattern in C++
Print a right half, left half, and full pyramid of stars in one C++ program. A review sheet that compares the three loop formulas side by side for the same rows.
1#include <iostream>2using namespace std;34int main() {5 int rows;67 cout << "Enter number of rows: ";8 cin >> rows;910 // Right Half Pyramid11 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 }1819 // Left Half Pyramid20 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 }3031 // Full Pyramid32 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 }4243 return 0;44}
Sample Output
Right Half Pyramid:
Label for block 1.
Full Pyramid:
Label for block 3; its last row has 9 stars.
In this one
- How three patterns reuse one outer loop shape
- Which inner formula belongs to which pyramid
- Why the pad is two spaces in one pattern and one in another
- How labels keep the output readable
How it works
- 1
Read rows (5).
- 2
Print the right half pyramid with j <= i.
- 3
Print the left half pyramid with rows - i pads first.
- 4
Print the full pyramid with 2i - 1 stars.
Edge cases
rows = 0
Enter 0.
Only the three labels print, with empty space under each.
Mixed widths
Use " " pads in the full pyramid.
The full pyramid becomes lopsided because its stars are only one character wide.
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.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which block prints 2i - 1 stars per row?
Pick an answer to check it.
Question 2
Why does the left half use two-space pads?
Pick an answer to check it.
Questions people ask
Why put three patterns in one file?
It shows how small changes in the inner loops change the shape, which is easier to see side by side.
Do the labels affect the shapes?
No. They just start each block on a new labeled line.
Where is the detailed walk-through?
On the single pages: Right Half Pyramid, Left Half Pyramid, and Full Pyramid.