Right-Aligned Incremental Number Triangle in Python

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

What You’ll Learn

The right-aligned incremental triangle prints 1, then 2 3, then 4 5 6, … — a natural follow-up after Program 34’s zero-based i + j triangle. This tutorial covers the continuous counter k, fixed-width formatting, nested loops, a live preview, worked Python examples, edge cases, and complexity.

Shape Rule

Right-aligned triangle

Row i prints i numbers from counter k, with leading spaces while j > i.

Outer Loop

i = 1..rows

for i in range(1, rows + 1): — one growing row per iteration.

Inner Loop (j)

rows..1

for j in range(rows, 0, -1): — fixed width; spaces or numbers per column.

Counter k

%3d format

print(f"{k:3d}", end=""); k += 1 — continuous sequence with fixed-width columns.

Live Preview

3–7 rows

Pick a row count and draw the right-aligned incremental triangle in the browser.

O(n²)

Complexity

Total prints = n(n+1)/2 — work scales as .

Introduction

A right-aligned incremental number triangle prints a continuous sequence: 1, then 2 3, then 4 5 6, and so on. With rows = 5, numbers shift right each row thanks to leading spaces.

In Python you use nested loops with a counter k: print " " while j > i, otherwise print(f"{k:3d}", end=""); k += 1, then print().

Why it matters?

It combines nested loops, a running counter, and formatted output — a step after Program 34’s formula-based triangle.

Key Highlights

Counter k

Continuous sequence.

j > i spaces

Right alignment.

%3d

Fixed-width columns.

Series Foundation

Follow Program 34; continue to Program 36 (decreasing) next.

In short: outer i = 1..rows, inner j = rows..1, spaces while j > i, else :3d with k += 1, then print().

📝 Problem & Approach

Given rows = 5, print a right-aligned incremental triangle: counter k starts at 1, leading spaces while j > i, then fixed-width numbers.

Python
# rows = 5
#              1
#           2  3
#        4  5  6
#     7  8  9 10
#11 12 13 14 15

Inputs & Outputs

ItemTypeDescription
rowsintTriangle height — number of lines to print.
iintOuter loop — current row (1 to rows).
jintInner loop — fixed width from rows down to 1.
kintContinuous counter — starts at 1, increments per printed number.

Minimal workflow

Pseudocode
k = 1
for i from 1 to rows:
    for j from rows down to 1:
        if j > i: print 3 spaces
        else: print k in width 3; k += 1
    print newline

Approach comparison

ApproachIdeaBest for
Fixed rows1, 2 3, …Learning and interviews
User-input rowsint(input(...))Configurable triangle size
Compact tracerows = 3 on paper firstDebugging loop bounds

⚡ Quick Reference

GoalPattern
Outer loopfor i in range(1, rows + 1):
Inner loopfor j in range(rows, 0, -1):
Leading spacesif j > i: print(" ", end="")
Print numberprint(f"{k:3d}", end=""); k += 1
End the rowprint()
User inputint(input(...))

📋 Fixed vs User Input vs Compact Demo

Same right-aligned incremental triangle — different ways to control the row count.

Outer loop
i = 1..rows

One growing row per iteration

Counter
k += 1

Continuous sequence

Inner loop
j = rows..1

Fixed width per row

Learning tip
j > i

Print spaces, else number

Context

When This Pattern Shows Up

Reach for this pattern when teaching formatted console output, continuous counters, and right-aligned triangles.

  1. After Program 34

    Natural follow-up — adds right alignment and a continuous counter instead of a per-cell formula.

  2. Formatted output drills

    Practice :3d and fixed-width columns before tackling larger patterns.

  3. Console I/O practice

    Combine loops with input() and try/except ValueError for flexible row counts.

  4. Gateway to variants

    Compare Program 30 (descending digits) and Program 36 (decreasing sequence) next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, formatted output, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 3 and 7 and draw the right-aligned incremental triangle in the browser.

Try 3, 5, or 7. Rows between 3 and 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Python programs — fixed rows, user input, and a smaller trace demo. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the right-aligned incremental triangle with counter k and :3d formatting.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

Python
k = 1

for i in range(1, 6):
    for j in range(5, 0, -1):
        if j > i:
            print("   ", end="")
        else:
            print(f"{k:3d}", end="")
            k += 1
    print()

How It Works

When i = 1, the inner loop prints four space groups then 1. When i = 5, no leading spaces — output 11 12 13 14 15 with fixed-width columns.

📈 User Input

Read the row count with input() and int() instead of hard-coding 5.

Example 2 — User input rows

Read rows with input() and int(); the inner loop uses rows as the fixed width.

Python
rows = int(input("Enter rows: "))
if rows < 1:
    raise SystemExit

k = 1
for i in range(1, rows + 1):
    for j in range(rows, 0, -1):
        if j > i:
            print("   ", end="")
        else:
            print(f"{k:3d}", end="")
            k += 1
    print()

How It Works

Same counter and formatting core as Example 1; only rows comes from user input instead of being hard-coded as 5. Non-numeric input raises ValueError with bare int(input()) — use try/except for safer labs.

⚡ Smaller Demo

Run with rows = 3 to trace every row on paper before scaling up.

Example 3 — Compact rows = 3

Same nested-loop counter with a smaller row count for quick tracing.

Python
rows = 3
k = 1

for i in range(1, rows + 1):
    for j in range(rows, 0, -1):
        if j > i:
            print("   ", end="")
        else:
            print(f"{k:3d}", end="")
            k += 1
    print()

How It Works

Only rows changes from 5 to 3 — the counter and spacing logic stays identical. Trace i = 1, 2, 3 on paper to see how leading spaces shrink each row.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed for fixed rows; use input() when reading. Set k = 1 and loop variables i, j with rows = 5.

Setup
2

Outer loop walks rows

for i in range(1, rows + 1): — ascending outer loop; one right-aligned row per iteration.

Row
3

Inner loop (j)

for j in range(rows, 0, -1): — fixed width; spaces while j > i, else print k.

Width
4

Print counter

print(f"{k:3d}", end=""); k += 1 — fixed-width columns; counter continues across rows.

Counter
5

New line

print() ends the row after the inner loop finishes.

Break
=

Right-aligned triangle complete

Total numbers = n(n+1)/2O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of i, leading spaces, numbers printed from k, and full row output.

iLeading space groupsNumbers printedRow output
1411
232, 32 3
324, 5, 64 5 6
417, 8, 9, 107 8 9 10
5011, 12, 13, 14, 1511 12 13 14 15

Leading space groups per row = rows - i — zero when i = rows. Total numbers printed = rows(rows+1)/2.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: flip j > i to j <= i for spaces and watch alignment break.

2. Pattern Series Base

Foundation for right-aligned variants and continuous counter patterns.

Example: compare with Program 30 (descending digits) and Program 36 (decreasing sequence).

3. Console Formatting Drills

Practice :3d formatting and fixed-width columns.

Example: remove :3d and watch two-digit values misalign.

4. Padding character

Add three-space groups for alignment once the two-loop structure works.

Example: use a single space instead of " " and watch columns drift.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed numbers for rows = 5 — total is 1+2+3+4+5 = 15.

6. Input Validation Labs

Pair the pattern with try/except ValueError and positive-row validation.

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

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner Python courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace i, j, and k on paper for rows = 3 before coding — watch how leading spaces shrink each row.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Declare k Outside Loops

    Counter k must start at 1 before the outer loop and persist across rows.

  2. 2. Call try/except ValueError

    Avoid undefined behavior when the user types letters instead of a number.

  3. 3. Keep newline outside inner loop

    Only call print() after the inner loop finishes the row.

  4. 4. Trace k on Paper

    Write the next value of k for each (i, j) pair before coding the loops.

  5. 5. Dry-Run rows = 3

    Trace i = 1..3 on paper before coding the full rows = 5 demo.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put print() inside the inner loop.

Common Pitfalls

Mistakes that commonly break right-aligned incremental triangles.

  1. 1. Newline Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use print(f"{k:3d}", end=""); k += 1; print() only after the inner loop.

  2. 2. Resetting k Each Row

    Putting k = 1 inside the outer loop restarts the sequence on every row.

    → Declare k = 1 once before the outer loop; only increment with k += 1 when printing.

  3. 3. Wrong Space Width

    Single spaces instead of " " break column alignment with :3d.

    → Print three spaces while j > i to match the fixed-width number columns.

  4. 4. Skipping %3d

    Plain print(k, end="") makes two-digit values crowd earlier columns.

    → Use print(f"{k:3d}", end=""); k += 1 for consistent column width.

  5. 5. Bare int(input())

    Letters or empty input raise ValueError with bare int(input()).

    → Catch ValueError and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is just 1 with leading spaces — one value, one row.

rows = 0

Empty pattern

Outer loop never runs when rows < 1 — print nothing or show a message.

Negative

rows < 1

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

rows = 2

Smallest triangle

Two rows: 1 and 2 3.

Bad input

Non-numeric input

Bare int(input()) raises ValueError on bad input — use try/except first.

Large rows

Large row count

Total numbers = rows(rows+1)/2 — grows quadratically with rows.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Decreasing sequence

  • Continue with Program 36
  • Right-aligned triangle with decreasing numbers

2. Descending digits

  • Review Program 30
  • Same j > i spacing, different fill

3. Counter trace

  • Prove on paper: after row i, k = i(i+1)/2 + 1
  • Each row adds i more numbers

4. Safe input loop

  • Validate rows >= 1 after reading input
  • Then draw the triangle

Notes

  • Counter rule. Declare k = 1 before loops. Inner loop runs j = rows..1 — print spaces while j > i, else :3d with k += 1.
  • print(f"{k:3d}", end=""); k += 1 stays on the line; print() advances — mix them carefully.
  • Validate rows >= 1 for interactive programs; rows = 1 prints a single 1.
  • Leading space groups = rows - i — compare with Program 30 where digits descend instead of a counter.

Quick Takeaway: outer i = 1..rows, inner j = rows..1, spaces while j > i, else :3d with k += 1, then print().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The right-aligned incremental number triangle is a compact lesson in nested loops, continuous counters, and formatted output: print spaces while j > i, use print(f"{k:3d}", end=""); k += 1 for each number, and end each row with print(). Master the fixed-rows version, then try user input and a smaller trace demo.

Practice the three examples above, then continue to Program 36 for the decreasing right-aligned sequence.

Keep k outside the outer loop — validate rows when reading from the console.

💡 Best Practices

✅ Do

  • Use for i in range(1, rows + 1): in the outer loop
  • Inner: for j in range(rows, 0, -1): with fixed width
  • Counter: print(f"{k:3d}", end=""); k += 1
  • Wrap int(input()) in try/except ValueError
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call print() inside the inner loop
  • Reset k = 1 inside the outer loop
  • Use single spaces instead of " " for alignment
  • 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 triangle

Print the pattern the beginner-friendly way.

5
Core concepts
02

j > i

Leading spaces

Code
0 03

%3d

Fixed width

Code
04

Row break

print() after the inner loop

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Numbers keep increasing across rows without resetting — row 1 prints 1, row 2 prints 2 3, row 3 prints 4 5 6, and so on.
Before printing numbers on each row, the program prints three spaces while j > i. This indents the left side so numbers shift right.
The format specifier reserves 3 columns per number (right-aligned), keeping columns aligned when values become two digits.
k is set to 1 before the loops and increases with k += 1 each time a number prints, so the sequence continues across rows.
Program 30 prints descending digits per row. Program 35 uses a continuous counter k with fixed-width formatting.
Replace 5 with rows in the outer loop bound — see Example 2.
O(n²) for n rows because total prints are 1 + 2 + ... + n = n(n+1)/2.
Use a try/except ValueError around int(input()) or check the raw string with .isdigit() before converting so bad input does not crash the script.
Only one row prints — a single 1 with leading spaces.

Did you Know? 🔊

A counter k starts at 1 and increments every time a number is printed. Leading spaces appear while j > i, and print(f"{k:3d}", end="") keeps columns aligned as values grow past single digits.

Continue to Program 36

Move on to the right-aligned decreasing number sequence in the Python number-pattern series.

Program 36 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