Right-Aligned Increasing Number Triangle Pattern in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Alignment

What You’ll Learn

The right-aligned increasing number triangle prints 1, then 1 2, then 1 2 3, and so on — with leading spaces so each row aligns on the right. This tutorial covers the space loop, number loop, live preview, algorithm steps, worked Java examples, edge cases, and complexity.

Shape Rule

Growing rows

Row i prints numbers 1..i; leading spaces right-align the triangle.

Space Loop

j = rows..i+1

for (j = rows; j > i; j--) prints rows - i leading spaces.

Number Loop

1..i per row

System.out.format("%2d", k) prints k = 1..i on every row.

Outer Loop

Row index i

for (i = 1; i <= rows; i++) walks each row of the triangle.

Live Preview

1–20 rows

Pick a row count and draw the right-aligned increasing number triangle instantly in the browser.

O(n²)

Complexity

Prints n(n+1)/2 numbers across n rows — iterations; extra memory stays O(1).

Introduction

A right-aligned increasing number triangle prints 1, then 1 2, then 1 2 3, up to rows. With rows = 5, the widest row sits flush right and shorter rows indent from the left.

In Java you use an outer loop for each row, a space loop that prints rows - i spaces, and a number loop that prints System.out.format("%2d", k) for k = 1..i.

Why it matters?

It teaches indent-then-content alignment — the same trick used for pyramids, diamonds, and right-aligned star patterns.

Key Highlights

Two Inner Loops

Space loop first, then number loop — both run on every row.

Leading Spaces

rows - i spaces shrink each row toward the right edge.

%2d Formatting

Two-character fields keep columns aligned when numbers reach two digits.

Series Foundation

Follow Program 42 hollow square; continue to Program 44 number diamond.

In short: for each row i, print rows - i spaces, then print numbers 1..i with %2d, then call System.out.println().

📝 Problem & Approach

Given a positive integer rows (e.g. 5), print a right-aligned triangle: row i shows numbers 1..i with leading spaces.

Java
// rows = 5 (conceptual shape)
//         1
//       1 2
//     1 2 3
//   1 2 3 4
// 1 2 3 4 5

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle rows to print (typically ≥ 1).
Printed outputtextRight-aligned rows of increasing numbers; row i has i values.

Minimal workflow

Pseudocode
for i from 1 to rows:
    print (rows - i) spaces
    for k from 1 to i: print k with %2d
    print newline

Approach comparison

ApproachIdeaBest for
Space + number loopsLeading spaces, then 1..i with %2dLearning and interviews
User-input sizesc.nextInt();Flexible console programs
Left-aligned triangleSkip the space loopContrast with right alignment

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= rows; i++)
Print spacesfor (j = rows; j > i; j--)
Print numbersfor (k = 1; k <= i; k++) + %2d
End the rowSystem.out.println();
Program 42 contrastHollow square uses a border if; this pattern uses spaces + increasing numbers

📋 Space Loop vs Number Loop vs Combined

Same triangle row — how leading spaces and numbers work together.

Space loop
j = rows; j > i; j--

Prints rows - i leading spaces

Number loop
k = 1..i

Prints System.out.format("%2d", k)

Row width
i numbers

Row i always prints i numbers

Learning tip
trace i=3

Dry-run row 3: two spaces then 1 2 3

Context

When This Pattern Shows Up

Reach for this pattern when teaching indent-then-content alignment with nested loops.

  1. First lab exercise

    Classic follow-up after hollow squares and centered pyramids.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with Scanner for a flexible row count.

  4. Gateway to variants

    Compare with Program 42 (hollow square), then continue to Program 44 (number diamond).

  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, output sequencing, and O(n²) thinking.

🔮 Live Preview

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

Try 5, 7, or 10. Larger values still work up to 20.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed row count, Scanner input, and a left-aligned variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with a space loop and number loop per row.

Example 1 — Fixed rows = 5

Hard-coded size — nested loops and a space loop build each row.

Java
public class RightAlignedNumberTriangle {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            for (int j = rows; j > i; j--) {
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.format("%2d", k);
            }
            System.out.println();
        }
    }
}

How It Works

When i = 1, the space loop prints four spaces, then one formatted 1. When i = 3, two spaces precede 1 2 3 — the triangle grows downward and right.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read the row count with Scanner.nextInt() (check hasNextInt() in real apps).

Java
import java.util.Scanner;

public class RightAlignedNumberTriangleInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int rows = sc.nextInt();

        for (int i = 1; i <= rows; i++) {
            for (int j = rows; j > i; j--) {
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.format("%2d", k);
            }
            System.out.println();
        }

        sc.close();
    }
}

How It Works

Same nested-loop core as Example 1; only the source of rows changes. Non-numeric input throws InputMismatchException with nextInt() — check hasNextInt() for safer labs.

⚡ Readability Variant

Remove the space loop to print a completely left-aligned triangle.

Example 3 — Left-Aligned Triangle

Skip the space loop so numbers start at the left margin — a common contrast exercise.

Java
public class LeftAlignedNumberTriangle {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            for (int k = 1; k <= i; k++) {
                System.out.format("%2d", k);
            }
            System.out.println();
        }
    }
}

How It Works

Same number loop; removing the leading-space loop leaves rows flush left.

🧠 How the Algorithm Prints Rows

1

Set up

System.out is built in; use Scanner when reading input. Set rows (fixed or from input).

Setup
2

Outer loop (rows)

for (i = 1; i <= rows; i++) — walks each row of the triangle.

Row
3

Space loop (align)

for (j = rows; j > i; j--) prints rows - i leading spaces.

Spaces
4

Number loop (1..i)

System.out.format("%2d", k) for k = 1..i, then println() ends the row.

Numbers
=

Right-aligned number triangle complete

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

🔎 Worked Walkthrough — rows = 5, row i = 3

Trace one middle row to see spaces and numbers combine.

StepLoopPrints
Spacesj = 5, 4 (2 times)
Numbersk = 11
Numbersk = 22
Numbersk = 33

Row output: 1 2 3 — total numbers for full triangle: 1+2+3+4+5 = 15 = n(n+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: remove the space loop and watch rows snap left.

2. Pattern Series Base

Foundation for number diamonds, centered pyramids, and mirrored patterns.

Example: mirror rows downward to build Program 44’s diamond.

3. Console Formatting Drills

Practice System.out.print vs row newline without complex math.

Example: put System.out.println() inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: print 1, 12, 123 without spaces between digits.

5. Complexity Intuition

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

Example: count printed numbers for n = 5 → 15.

6. Input Validation Labs

Pair the pattern with Scanner and positive-row checks.

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 Java courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a misaligned or left-aligned shape.

  2. 2. Minimal Concepts

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

  3. 3. Easy to Extend

    Invert, center, left-align, or swap digits for stars with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the space-loop version first; then try the left-aligned triangle in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use rows (or n) and keep i/j for row/column — or rename to row/col.

  2. 2. Prefer Scanner

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

  3. 3. Keep System.out.println() Outside

    Only call System.out.println() after the inner loop finishes the row.

  4. 4. Use Ternary for Compact Code

    One-liner for spaces: System.out.print(" ".repeat(rows - i)); before the number loop.

  5. 5. Dry-Run One Small n

    Trace rows = 3 on paper before coding larger demos.

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

Common Pitfalls

Mistakes that commonly break right-aligned number triangles.

  1. 1. System.out.println() Inside the Inner Loop

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

    → Use System.out.print for spaces and numbers; System.out.println() only after both inner loops.

  2. 2. Wrong Space Count

    Using j = 1..i for spaces under-indents rows and breaks right alignment.

    → Keep for (j = rows; j > i; j--) to print rows-i leading spaces.

  3. 3. Forgetting the Row Break

    Omitting System.out.println() glues every row onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Unchecked Scanner input

    Letters or empty input throw InputMismatchException.

    → Prefer Scanner and re-prompt on failure.

  5. 5. Missing %2d Format

    Printing bare k without %2d breaks alignment once values reach two digits.

    → Use System.out.format("%2d", k) so columns stay aligned.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is one indented 1 when right-aligned.

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

Many rows

Output grows as n(n+1)/2 numbers plus spaces — fine for labs, noisy for huge n.

Bad input

Non-numeric Scanner input

Unchecked Scanner leaves rows unset — call sc.hasNextInt() first.

Fill char

Left-aligned triangle

Remove the space loop — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Number diamond pattern

  • Mirror rows after the widest line
  • Continue with Program 44

2. Left-aligned triangle

  • Remove the leading-space loop
  • Same number loop as Example 3

3. Reverse triangle

  • Loop i from rows down to 1
  • Keep the same space formula

4. Concatenated digits

  • Print 1, 12, 123 without spaces
  • Adjust indentation for alignment

Notes

  • Number count. Total numbers printed for n rows is n(n+1)/2; leading spaces add roughly the same order of characters.
  • print stays on the line; println advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print one indented 1.
  • Use System.out.format("%2d", k) so columns stay aligned as values grow.

Quick Takeaway: space loop for alignment, number loop for 1..i, %2d formatting, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
Left-aligned triangle (Example 3)O(rows²)O(1)
Wrap Up

🎉 Conclusion

The right-aligned increasing number triangle combines nested loops with a simple alignment pattern — a natural step after hollow squares and pyramids. Master the fixed-rows version first, then try user input and the left-aligned triangle.

Practice the three examples above, then continue to Program 44 for the number diamond pattern.

Every row prints i numbers — keep println() only after both inner loops finish.

💡 Best Practices

✅ Do

  • Explain space loop and number loop before coding
  • Use %2d and println() after each row
  • Validate rows ≥ 1 for interactive programs
  • Check Scanner return value before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call System.out.println() inside the inner digit loop
  • Skip the space loop (you get a left-aligned triangle instead)
  • Use one space per indent when %2d needs two
  • 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 increasing number triangle

Print the pattern the beginner-friendly way.

5
Core concepts
02

Space loop

rows - i spaces

Code
03

Number loop

Print 1..i with %2d

Logic
n 04

Total visits

n(n+1)/2 numbers

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Each row prints leading spaces before the numbers. As i grows, the space count (rows - i) shrinks, pushing rows to align on the right.
The outer loop sets the row index i. An inner loop prints k from 1 to i on every row.
for (j = rows; j > i; j--) prints rows-i spaces before the numbers, creating the right alignment.
Remove the leading-space loop. Printing only numbers 1..i naturally left-aligns the triangle — see Example 3.
%2d prints each number in a two-character field so columns stay aligned when values reach two digits.
O(n²) for n rows because total printed numbers are 1+2+...+n = n(n+1)/2.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.
You get a single row with just the number 1 (with optional leading spaces depending on alignment).

Did you Know? 🔊

Each row prints numbers 1..i and leading spaces push the row to the right — fewer spaces as i grows, which creates the right-aligned triangle.

Continue to Program 44

Move on to the centered number diamond pattern in the Java number-pattern series.

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