C++ Right-Aligned Triangle Star Pattern

Beginner
6 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A right-aligned right-angled triangle grows by one star per row, but the right edge stays flush — you get there by printing leading spaces before the stars.

Remember
Rule: on row i, print (rows - i) spaces, then i stars

    *
   **
  ***
 ****
*****     ← 5 rows (right edge straight)

Compared with Program 1, you keep the same i star counts and add a second inner loop for (rows - i) spaces. That is the usual stepping stone toward centered pyramids.

How to Solve It

Two ways to emit the same shape — start with nested space/star loops, then optionally shorten with string.

MethodIdeaBest for
Nested loopsOuter = rows; first inner = spaces, second = starsLearning, interviews, exams
string() shortcutBuild padding and star run in one call eachShorter demos once formulas click

Pseudocode

Pseudocode
for i from 1 to rows:
    print (rows - i) spaces (no newline)
    print i stars (no newline)
    print newline

Cheat sheet

GoalPattern
Walk each rowfor (i = 1; i <= rows; ++i)
Leading spacesfor (j = 1; j <= rows - i; ++j) cout << " ";
Print i starsfor (k = 1; k <= i; ++k) cout << "*";
End the rowcout << "\n";
Row width check(rows - i) + i == rows
One-line shortcutcout << string(rows - i, ' ') << string(i, '*') << "\n";
Invert laterGrow spaces, shrink stars → Program 4

Printing Stars vs Starting a New Line

APIEffectUse for
cout << " " / "*"Stays on the same lineEach space and each star
cout << "\n"Ends the current lineAfter both inner loops

Live Preview

Change the row count and the right-aligned triangle updates instantly — including the star total.

Whole numbers from 1 to 20. Each row is exactly rows characters wide.

Live result 5 rows · 15 stars
    *
   **
  ***
 ****
*****

Worked Walkthrough — rows = 4

Trace spaces, stars, and total width for each outer-loop value of i.

iSpaces rows - iStars iWidthPrinted row
1314*
2224**
3134***
4044****

Star total: 1 + 2 + 3 + 4 = 10 = 4×5/2 — same as Program 1. Every row width is 4, which keeps the right edge flush. That is why time is O(n²).

C++ Programs

Three complete programs: nested space/star loops, console input, and a string shortcut. Use View Output to reveal sample results.

Example 1 — Fixed rows = 5

Hard-coded height — space loop first, then star loop.

C++
#include <iostream>
using namespace std;

int main() {
    int rows = 5;

    for (int i = 1; i <= rows; ++i) {
        for (int j = 1; j <= rows - i; ++j) {
            cout << " ";
        }
        for (int k = 1; k <= i; ++k) {
            cout << "*";
        }
        cout << "\n";
    }

    return 0;
}

How It Works

1. Set height. rows = 5 means five lines; every line is 5 characters wide.

2. Outer loop picks the row. i runs from 1 to rows.

3. Spaces, then stars. Print rows - i spaces, then i stars with cout.

4. Break the line. cout << "\n" after both inner loops starts the next row.

When i = 1 you get 4 spaces and 1 star; when i = 5 you get 0 spaces and 5 stars.

Example 2 — User Input Version

Read the height at runtime. Check cin.fail() in real apps (shown in the tip below).

C++
#include <iostream>
using namespace std;

int main() {
    int rows;

    cout << "Enter the number of rows: ";
    cin >> rows;

    for (int i = 1; i <= rows; ++i) {
        for (int j = 1; j <= rows - i; ++j) {
            cout << " ";
        }
        for (int k = 1; k <= i; ++k) {
            cout << "*";
        }
        cout << "\n";
    }

    return 0;
}

How It Works

1. Prompt and read. Ask for a row count, then store it with cin >> rows.

2. Same space/star core. Only the source of rows changes — the print logic matches Example 1.

3. Safer input tip. Bad input sets cin’s fail bit. Prefer:

Safer input
if (!(cin >> rows) || rows < 1) {
    cout << "Enter a positive whole number.\n";
    return 1;
}

Example 3 — string() for Spaces and Stars

Build each row’s padding and star run in one call each — same shape, no explicit character loops.

C++
#include <iostream>
#include <string>
using namespace std;

int main() {
    int rows = 5;

    for (int i = 1; i <= rows; ++i) {
        cout << string(rows - i, ' ')
             << string(i, '*')
             << "\n";
    }

    return 0;
}

How It Works

1. Same outer loop. Still walk i from 1 to rows.

2. Build each segment. string(rows - i, ' ') is the margin; string(i, '*') is the star run.

3. Print and advance. Chain both strings into cout, then end the line with "\n".

Learn the two-loop version first (Examples 1–2) so you can explain both bounds in an interview; treat this as a polish shortcut afterward.

Edge Cases & Pitfalls

Check these before calling the solution done.

No space loop

Left-aligned again

Skipping the space loop reprints Program 1. Print rows - i spaces before the stars.

Swapped counts

Broken right edge

Using i spaces and rows - i stars no longer flush-aligns on the right. Keep spaces = rows - i and stars = i.

Tabs

Uneven columns

Always print the space character " ", not tabs — tab width varies and skews the edge.

rows = 1

Single star

0 spaces + 1 star — same as Program 1 for n = 1. A good sanity check.

rows ≤ 0

Empty output

Outer loop never runs. Validate and re-prompt for interactive programs.

Bad input

Check cin.fail()

Letters leave cin in a failed state — prefer if (!(cin >> rows) || rows < 1).

Time and Space Complexity

ProgramTimeExtra space
Nested space/star loops (Examples 1–2)O(rows²)O(1)
string() shortcut (Example 3)O(rows²)O(rows) temporary per row string

Each of n rows prints exactly n characters (spaces + stars). Star total is still n(n+1)/2 — quadratic in n.

Key Takeaways

  • Rule: print rows - i spaces, then i stars.
  • Same stars as Program 1: only the leading spaces change the picture.
  • Break the row: call cout << "\n" only after both inner loops.
  • Complexity: O(n²) time; O(1) extra space for nested loops.

One line: for each row i, print rows - i spaces and i stars, then cout << "\n".

Frequently Asked Questions

After choosing row i, print (rows - i) space characters, then print i stars. Row 1 has rows minus 1 spaces and one star; row rows has no spaces and rows stars. Stars line up along the right edge.
Spaces and stars change with different formulas each row. One inner loop prints spaces from 1 to rows minus i, and a second prints stars from 1 to i. Without the space loop, output stays left-aligned like Program 1.
Program 1 prints only i stars per row. Program 3 prints (rows - i) spaces first, then i stars, so the same star counts appear shifted to the right.
cout << "*" stays on the same line. cout << "\n" ends the current line. Spaces and stars use cout without a newline; the row break uses cout << "\n" after both inner loops.
Every row prints exactly rows characters before the newline: (rows - i) spaces plus i stars.
O(n²) for n rows. Each row prints on the order of n characters (spaces plus stars), for n rows.
Yes. cout << string(rows - i, ' ') << string(i, '*') << "\n" builds each row without explicit inner character loops.
After cin >> rows, check cin.fail() or use if (!(cin >> rows)) to handle bad input.

Did you know?

Right-aligned and left-aligned triangles use the same star counts per row; only leading spaces change. Each row prints exactly rows characters before the newline: (rows - i) + i = rows.

Next: Inverted Right-Aligned

Grow the leading spaces and shrink the stars for an upside-down right edge.

Program 4 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful