Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Left Half Pyramid in C++

Print a left half pyramid in C++ by printing rows - i padding spaces before i stars on each line. Shows why the padding is two spaces wide to match "* ".

BeginnerPattern ProgramsExample 2 of 6
left-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 // Print spaces
12 for (int j = 1; j <= rows - i; j++) {
13 cout << " ";
14 }
15 // Print stars
16 for (int j = 1; j <= i; j++) {
17 cout << "* ";
18 }
19 cout << endl;
20 }
21
22 return 0;
23}

Sample Output

*

Row 1: four two-space pads, then one star.

* * * * *

Row 5: no padding.

In this one

  • How a padding loop shifts a pattern to the right
  • Why the pad width must match the star width
  • How rows - i shrinks as i grows
  • The order of the two inner loops

How it works

  1. 1

    Read rows (5).

  2. 2

    For each row i, print rows - i pads of two spaces.

  3. 3

    Then print i copies of "* ".

  4. 4

    End the line with endl.

Edge cases

Single space pad

Change " " to " ".

The right edge stops lining up because each star takes two characters, so the triangle leans.

rows = 1

Enter 1.

Zero pads and one star: just *.

What's going on

Same star counts as the right-half pyramid, shoved right with spaces. Row i: (rows − i) space-pairs, then i stars.

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

Spaces first:

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

cout << " ";

Two spaces per pad so they line up with "* " (star plus space). One space and the triangle leans.

Then the same star loop as right-half: j from 1 to i, "* ".

Walk 5:

i=1: 4 pads, 1 star
i=2: 3 pads, 2 stars
i=3: 2 pads, 3 stars
i=4: 1 pad, 4 stars
i=5: 0 pads, 5 stars — flush left

Print spaces before stars. Stars first and you get the right-half again.

rows - i going negative never happens here because i ≤ rows.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

On row 2 of 5 rows, how many pad units print?

Pick an answer to check it.

Question 2

What happens if stars print before spaces?

Pick an answer to check it.

Questions people ask

Why two loops inside the outer loop?

One prints the spacing, the other prints the stars. Each has its own count.

How do I make it upside down?

Run i from rows down to 1 with the same inner loops.

Why do some consoles show it crooked?

A proportional font makes spaces narrower than stars. Use a monospaced font.