Java Number Triangle Pattern (Fill with N)

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

What Is This Pattern?

A fill-with-n number triangle prints an ascending run from the row start to n, then pads the rest of the row with n so every line has the same width.

Remember
Rule: for i from n down to 1,
      print i..n, then pad with n until width = n

5 5 5 5 5
4 5 5 5 5
3 4 5 5 5
2 3 4 5 5
1 2 3 4 5     ← n = 5

Two inner loops do the work: sequence (j from i to n) then fill (i - 1 times with n). Companion to Program 18 (parity-based streams) — here the focus is fixed-width padding.

How to Solve It

Descend the outer start, print the ascending run, then pad to width n.

MethodIdeaBest for
Sequence + fillPrint i..n, then pad with nLearning, interviews, exams
Custom fillSame sequence; pad with a separate constantWhen the fill value should differ from n

Pseudocode

Pseudocode
for i from n down to 1:
    for j from i to n:
        print j
    for j from 1 to i - 1:
        print n
    print newline

Cheat sheet

GoalPattern
Descend startsfor (int i = n; i >= 1; i--)
Ascending runfor (int j = i; j <= n; j++) System.out.print(j + " ");
Pad to widthfor (int j = 1; j < i; j++) System.out.print(n + " ");
End the rowSystem.out.println();
Row widthAlways n numbers
Custom padPrint fill instead of n in the second loop

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.printStays on the same lineEach sequence number and each pad
System.out.printlnEnds the current lineAfter both inner loops

Print numbers without a newline, then end the row once.

Live Preview

Change the width n and the fill-with-n triangle updates instantly.

Whole numbers from 1 to 12. Tap a chip or type a value — the preview redraws as you go.

Live result n = 5 · 5 rows · 25 numbers
5 5 5 5 5
4 5 5 5 5
3 4 5 5 5
2 3 4 5 5
1 2 3 4 5

Worked Walkthrough — n = 4

Trace each row’s sequence, pad count, and full line.

iSequencePadsPrinted row
443 × 44 4 4 4
33 42 × 43 4 4 4
22 3 41 × 42 3 4 4
11 2 3 401 2 3 4

Every row has width 4. Total numbers: 4 × 4 = 16 = n² — that is why time is O(n²).

Java Programs

Three complete programs: fixed n = 5, Scanner input, and a custom fill constant. Use View Output to reveal sample results.

Example 1 — Fixed n = 5

Hard-coded width — sequence loop first, then pad with n.

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

        for (int i = n; i >= 1; i--) {
            for (int j = i; j <= n; j++)
                System.out.print(j + " ");

            for (int j = 1; j < i; j++)
                System.out.print(n + " ");

            System.out.println();
        }
    }
}

How It Works

1. Outer loop descends. i runs from n down to 1 — top row is mostly fill; bottom is the full sequence.

2. Sequence run. Print j from i to n.

3. Pad to width. Print n exactly i - 1 times so the row length stays n.

When i = 3, sequence prints 3 4 5, then two 5s pad the row.

Example 2 — Width Input

Read n at runtime. Prefer hasNextInt() before nextInt() in real apps.

Java
import java.util.Scanner;

public class FillWithNInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the triangle width: ");
        int n = sc.nextInt();

        for (int i = n; i >= 1; i--) {
            for (int j = i; j <= n; j++)
                System.out.print(j + " ");

            for (int j = 1; j < i; j++)
                System.out.print(n + " ");

            System.out.println();
        }
        sc.close();
    }
}

How It Works

1. Prompt and read. Ask for a width, then store it with sc.nextInt().

2. Same two-loop core. Both the sequence end bound and the fill value use n.

3. Safer input tip. Prefer:

Safer input
if (!sc.hasNextInt()) {
    System.out.println("Enter a positive whole number.");
    return;
}
int n = sc.nextInt();
if (n < 1) {
    System.out.println("Enter a positive whole number.");
    return;
}

Example 3 — Custom Fill Constant

Pad with fill = 9 while the sequence still runs up to n = 5.

Java
public class FillWithCustomConstant {
    public static void main(String[] args) {
        int n = 5;
        int fill = 9;

        for (int i = n; i >= 1; i--) {
            for (int j = i; j <= n; j++)
                System.out.print(j + " ");

            for (int j = 1; j < i; j++)
                System.out.print(fill + " ");

            System.out.println();
        }
    }
}

How It Works

1. Same sequence. Still print j from i to n.

2. Different pad. The second loop prints fill instead of n.

3. Same width. Each row still has exactly n numbers.

Edge Cases & Pitfalls

Check these before calling the solution done.

No fill

Uneven widths

Skipping the second loop leaves short top rows. Every row must print n numbers.

j <= i

Wrong pad count

The fill loop must be j < i (runs i - 1 times). Using j <= i over-pads.

println inside

Column of numbers

If println is inside either inner loop, each number lands on its own line. Use print for numbers; println only after both loops.

n = 1

Single 1

Output is just 1 — fill never runs. A good sanity check.

n ≤ 0

Empty output

The outer loop never runs. Validate and require n ≥ 1.

Bad input

Use hasNextInt

nextInt() throws on letters — prefer hasNextInt() and require a positive whole number.

Time and Space Complexity

ProgramTimeExtra space
Sequence + fill (Examples 1–3)O(n²)O(1)

Each of n rows prints exactly n numbers — total n² prints, still quadratic in n.

Key Takeaways

  • Rule: for i from n down to 1, print i..n, then pad with n.
  • Fixed width: every row prints exactly n numbers.
  • Break the row: call println only after both inner loops.
  • Complexity: O(n²) time; O(1) extra space.

One line: for each start i, print i..n, pad with n to width n, then println().

Frequently Asked Questions

When i = 5, the sequence loop prints j = 5 once, then the fill loop runs 4 times — all values are 5, so the row is 5 5 5 5 5.
The first inner loop prints the increasing sequence i..n. The second fills remaining positions with n so every row has the same width.
When i = 1, the sequence loop prints j = 1 to 5 and the fill loop runs zero times — no padding needed.
System.out.print stays on the same line with a trailing space. System.out.println ends the current line. Numbers use print; the row break uses println after both inner loops.
Replace n in the second loop with a separate fill constant — Example 3 on this page pads with 9 while the sequence still runs to 5.
Rows will have different widths — the top row may be short while the bottom row is full length.
O(n²) for width n because each of n rows prints n numbers.
Use sc.hasNextInt() before sc.nextInt(), require n ≥ 1, and reject non-numeric input — see Example 2 notes.

Did you know?

Each row prints an ascending sequence i..n, then pads with n so every row has width n. The second inner loop runs i - 1 times — still O(n²) total prints.

Next: Continuous Number Triangle

Move on to the continuous number triangle in the Java number-pattern series.

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