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

Right Half Pyramid in C++

Print a right half pyramid of stars in C++ with two nested for loops. Learn how the outer loop picks the row and the inner loop prints i stars on row i.

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}

Sample Output

*

Row 1: inner loop runs once.

* * * * *

Row 5: inner loop runs five times.

In this one

  • How nested loops map to rows and columns
  • Why the inner loop limit is i, not rows
  • Where endl must go so each row starts fresh
  • How this shape becomes the base for other patterns

How it works

  1. 1

    Read rows (5).

  2. 2

    Outer loop i = 1 to 5 handles one line per pass.

  3. 3

    Inner loop j = 1 to i prints "* " i times.

  4. 4

    endl ends the line after the inner loop.

Edge cases

rows = 0

Enter 0.

The outer condition 1 <= 0 is false, so nothing prints after the prompt.

endl inside the inner loop

Move cout << endl; inside the j loop.

Every star lands on its own line, giving 15 lines of single stars for 5 rows.

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.

Quiz

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

Question 1

How many stars are on row 4 of a 6-row right half pyramid?

Pick an answer to check it.

Question 2

What prints if the inner limit is rows instead of i?

Pick an answer to check it.

Questions people ask

How do I count stars for n rows?

1 + 2 + ... + n = n(n+1)/2. For 5 rows that is 15.

Can I use numbers instead of stars?

Yes, print j or i instead of "* ". See the number pattern page.

Why "* " with a space?

The space keeps stars apart so the triangle is easier to see.