Right-Aligned Right-Angled Triangle Star Pattern in Python

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Spaces + Stars

What You’ll Learn

The right-aligned triangle keeps the same star counts as Program 1, but adds a leading-space loop so the right edge stays straight. This tutorial covers the space formula, two inner loops, a live preview, algorithm steps, worked Python examples, edge cases, and complexity.

Shape Rule

Flush right

Same 1…n stars as Program 1, shifted right with leading spaces.

Space Loop

rows - i

Print rows - i spaces before the stars on row i.

Star Loop

i stars

Same as Program 1: print exactly i stars after the padding.

Fixed Width

n chars/row

Every row has (rows - i) + i = rows characters before the newline.

Live Preview

1–20 rows

Pick a row count and draw the right-aligned triangle instantly.

O(n²)

Complexity

n rows × Θ(n) characters each — O(n²) time, O(1) extra space.

Introduction

A right-aligned right-angled triangle grows by one star per row, but the right angle sits on the right edge. You get there by printing leading spaces before the stars.

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.

Why it matters?

Leading spaces are how console patterns create alignment and centering. Once this space loop clicks, pyramids and diamonds reuse the same idea.

Key Highlights

Spaces First

Print rows - i spaces, then stars.

Same Star Counts

Row i still has exactly i stars.

Two Inner Loops

One for padding, one for stars.

Gateway Pattern

Foundation for pyramids and diamonds.

In short: for each row i, print rows - i spaces, then i stars, then a newline — the right edge stays flush.

📝 Problem & Approach

Given a positive integer rows, print a right-aligned right-angled triangle of * characters with rows lines.

Python
# First 5 rows (spaces shown as ·)
# ····*
# ···**
# ··***
# ·****
# *****

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle lines (typically ≥ 1). Also the width of each line.
Printed outputtextRight-aligned rows: (rows - i) spaces + i stars.

Minimal workflow

Pseudocode
for i from 1 to rows:
    for j from 1 to (rows - i):
        print " " (no newline)
    for k from 1 to i:
        print "*" (no newline)
    print newline

Approach comparison

ApproachIdeaBest for
Two inner loopsSpaces then stars with separate countersLearning and interviews
"*" * shortcutBuild padding and stars as stringsShorter demos after formulas click

⚡ Quick Reference

GoalPattern
Walk each rowfor i in range(1, rows + 1):
Leading spacesfor j in range(1, rows - i + 1): print(" ", end="")
Print i starsfor k in range(1, i + 1): print("*", end="")
End the rowprint()
Width check(rows - i) + i == rows
String shortcutprint(" " * (rows - i) + "*" * i)

📋 Program 1 vs Program 3 vs Program 4

Same family — alignment and direction change the picture.

Program 1
left-aligned

Only i stars — no space loop

This page
spaces + stars

rows - i spaces, then i stars

Program 4
inverted + right

Growing spaces, shrinking stars

Interview tip
name both loops

Say padding formula before star formula

Context

When This Pattern Shows Up

Reach for right alignment when teaching leading spaces after a left-aligned triangle.

  1. After Program 1

    Natural next lab: keep star counts, add a space loop.

  2. Padding / alignment drills

    Practice two different per-row formulas in one figure.

  3. Pyramid precursor

    Centered pyramids reuse the same space formula idea.

  4. Fixed-width row thinking

    Every line spans exactly rows columns — easy to verify.

  5. Not a UI layout tool

    Console-style teaching pattern — not how you build app screens.

Key benefit: one small space loop that unlocks alignment, centering, and most later star patterns.

🔮 Live Preview

Choose a row count between 1 and 20 and draw the right-aligned triangle in the browser.

Try 5, 7, or 10. Each line will be that many characters wide.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Python programs — nested space/star loops, console input, and a "*" * shortcut. Click View Output to reveal sample console results.

📚 Getting Started

Print five right-aligned rows with classic nested loops.

Example 1 — Fixed rows = 5

Space loop first, then star loop — the standard textbook version.

Python
rows = 5

for i in range(1, rows + 1):
    for j in range(1, rows - i + 1):
        print(" ", end="")
    for k in range(1, i + 1):
        print("*", end="")
    print()

How It Works

When i = 1, print 4 spaces then 1 star. When i = 5, print 0 spaces then 5 stars. Every row has exactly 5 characters before the newline.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read rows with input() and int() (wrap in try/except ValueError in real apps).

Python
rows = int(input("Enter the number of rows: "))

for i in range(1, rows + 1):
    for j in range(1, rows - i + 1):
        print(" ", end="")
    for k in range(1, i + 1):
        print("*", end="")
    print()

How It Works

Same space/star core as Example 1; only the source of rows changes. Non-numeric input raises ValueError with bare int(input()) — use try/except for safer labs.

⚡ Shortcut Style

Same shape without explicit character loops.

Example 3 — " " * and "*" * Multiplication

Build each row’s padding and star run in one call each.

Python
rows = 5

for i in range(1, rows + 1):
    print(" " * (rows - i) + "*" * i)

How It Works

Same formulas as Example 1; "*" * replaces the two inner loops. Keep the nested-loop version for exams that want both bounds visible.

🧠 How the Algorithm Prints Rows

1

Set up

Set rows. Use i for the row, j for spaces, k for stars.

Setup
2

Outer loop (rows)

for i in range(1, rows + 1): walks from one star up to rows stars.

Row
3

Padding spaces

for j in range(1, rows - i + 1): print(" ", end="") shifts the star block right.

Align
4

Stars then newline

Print i stars with print("*", end=""), then print(). Row width is always rows.

Stars
=

Right-aligned triangle

Star total n(n+1)/2; O(n²) time, O(1) extra space.

🔎 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****

Check: every row has width 4. Star total: 1+2+3+4 = 10.

Use Cases

Where leading-space alignment (and this triangle) shows up beyond the homework prompt.

1. Teaching Padding

Clearest intro to a second inner loop for spaces.

Example: remove the space loop and recover Program 1.

2. Pyramid Warm-Up

Centered pyramids reuse rows - i (or similar) padding.

Example: Program 5 adds odd star counts.

3. Width Invariants

Assert every line has length rows while debugging.

Example: count printed chars before print().

4. Character Substitution

Swap * for digits once alignment works.

Example: print i instead of *.

5. Invert Next

Program 4 combines right alignment with shrinking stars.

Example: flip space growth direction.

6. Input Validation Labs

Pair with input validation and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: in interviews, say “Program 1 star counts plus rows - i spaces” before writing loops.

Advantages

Why this right-aligned pattern is a strong third exercise.

  1. 1. Builds Directly on Program 1

    Same star loop — only one new concept (leading spaces).

  2. 2. Easy Width Check

    Every row length equals rows — bugs show up immediately.

  3. 3. Unlocks Later Patterns

    Pyramids and diamonds reuse the same padding idea.

  4. 4. O(1) Extra Memory

    Streaming output needs only loop counters.

Pro Tip: master the two-loop version first; treat "*" * as a polish shortcut afterward.

Usage Tips

Small habits that keep right-aligned pattern code clean.

  1. 1. Spaces Before Stars

    Always print padding first — order matters for alignment.

  2. 2. Use Real Spaces, Not Tabs

    Tabs break alignment across fonts and editors.

  3. 3. Wrap int(input()) in try/except

    Avoid crashes when the user types letters instead of a number.

  4. 4. Verify Width = rows

    Mentally check (rows - i) + i on tip and last rows.

  5. 5. Dry-Run One Small n

    Trace rows = 3 or 4 on paper before coding larger demos.

Pro Tip: if the output looks left-aligned, you almost certainly forgot the space loop (or ran it with 0 iterations).

Common Pitfalls

Mistakes that commonly break right-aligned star triangles.

  1. 1. Forgetting the Space Loop

    You reprint Program 1 — left-aligned, not flush right.

    → Print rows - i spaces before the stars.

  2. 2. Swapping Space and Star Bounds

    Using i spaces and rows - i stars breaks the right edge.

    → Spaces = rows - i; stars = i.

  3. 3. Off-by-One on Spaces

    j < rows - i instead of j <= rows - i drops a needed space.

    → Use j <= rows - i for this formulation.

  4. 4. Mixing Tabs With Spaces

    Alignment looks fine in one editor and broken in another.

    → Always print the space character " ".

  5. 5. Blind int(input())

    Letters or empty input throw ValueError.

    → Catch ValueError and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single star

0 spaces + 1 star — same as Program 1 for n = 1.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Wide lines

Each line is n characters — fine for labs; may wrap on tiny terminals.

Bad input

Non-numeric ReadLine

int(input()) raises ValueError — validate first.

Last row

i == rows

Space loop runs 0 times — only stars, flush left and right.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Drop back to Program 1

  • Remove only the space loop
  • Confirm left-aligned output returns

2. Invert the alignment

  • Grow spaces and shrink stars
  • Continue with Program 4

3. Safe input loop

  • Validate input until rows >= 1
  • Then draw the triangle

4. Number triangle

  • Keep the space loop; print digits instead of *
  • Shows alignment is independent of fill

Notes

  • Same stars as Program 1. Only leading spaces change the picture.
  • Every row has width rows: (rows - i) + i = rows.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single star.
  • Next: Program 4 inverts this shape while keeping the right edge flush.

Quick Takeaway: print rows - i spaces, then i stars, then a newline — that is right alignment.

⏱️ Time and Space Complexity

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

Each of n rows prints Θ(n) characters (spaces + stars).

Wrap Up

🎉 Conclusion

The right-aligned triangle is Program 1 plus a leading-space loop: rows - i spaces, then i stars. That single idea unlocks alignment and most later console patterns.

Practice the three examples above, then continue to the inverted right-aligned triangle.

Spaces first, then stars — keep the width check (rows - i) + i == rows, and validate row counts when reading input.

💡 Best Practices

✅ Do

  • Explain spaces then stars before coding
  • Use rows - i spaces and i stars
  • Print real space characters, not tabs
  • Check that each row has width rows
  • Use try/except ValueError for interactive demos

❌ Don’t

  • Skip the space loop and expect right alignment
  • Swap the space and star formulas
  • Use j < rows - i when you meant <=
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this right-aligned pattern

Print the flush-right triangle the beginner-friendly way.

5
Core concepts
02

Spaces

rows - i

Formula
* 03

Stars

i (same as P1)

Formula
= 04

Width

Always rows

Check
O 05

Complexity

O(n²) time

Analysis

❓ 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.
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. print(" " * (rows - i) + "*" * i) builds each row without explicit inner character loops.
Wrap int(input()) in try/except ValueError so bad input does not crash the script.
You get a left-padded shape that no longer flush-aligns on the right, or an inverted look. Keep spaces = rows - i and stars = i.

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.

Continue to Inverted Right-Aligned Triangle

Keep the right edge flush while shrinking the star count each row.

Program 4 tutorial →

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