Java Number Triangle Pattern (Diagonal Fill)

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

What Is This Pattern?

A diagonal-fill number triangle starts each row at index i, then builds later values with res = res + k where k begins at rows − 1 and shrinks.

Remember
Rule: for i = 1..rows
        start with i; k = rows - 1
        next values: res = res + k; k--

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

Unlike Program 54 (space-filled X diamond), here every cell holds a number — filled as if walking down diagonals of a triangle.

How to Solve It

Print i first on each row; for later columns add a decreasing step k.

MethodIdeaBest for
Fixed rowsHard-code size; res + k stepsLabs and demos
Scanner inputSame logic; read rows at runtimeInteractive practice
Compact rowsStringBuilder without trailing spaceCleaner console output

Pseudocode

Pseudocode
for i from 1 to rows:
    k = rows - 1
    res = i
    for j from i to i+i-1:   // i values
        if i == j: print i
        else:
            res = res + k
            print res
            k = k - 1
    new line

Cheat sheet

GoalPattern
Set sizeint rows = 5;
Reset stepint k = rows - 1; each row
First valueif (i == j) print(j);
Next valueres = res + k; print(res); k--;
Inner spanfor (int j = i; j < i + i; j++)

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.printStays on the same lineEach number in the row
System.out.printlnEnds the lineAfter the inner loop finishes

Print values side by side, then break once per row.

Live Preview

Change the row count and the diagonal-fill triangle updates instantly.

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

Live result rows = 5 · values = 15
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15

Worked Walkthrough — rows = 5, row i = 3

Trace how res and k build 3 7 10.

StepjActionPrint
13i == j → print start3
24res = 3 + 4; k → 37
35res = 7 + 3; k → 210

Full row: 3 7 10. Each new row resets k to rows − 1 (here 4).

Java Programs

Three complete programs: fixed rows = 5, Scanner input, and compact StringBuilder rows. Use View Output to reveal sample results.

Example 1 — Fixed rows = 5

Hard-coded size — each row uses res + k stepping with k = rows - 1.

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

        for (int i = 1; i <= rows; i++) {
            int k = rows - 1;
            int res = i;

            for (int j = i; j < i + i; j++) {
                if (i == j) {
                    System.out.print(j + " ");
                } else {
                    res = res + k;
                    System.out.print(res + " ");
                    k--;
                }
            }
            System.out.println();
        }
    }
}

How It Works

1. Start the row. When i == j, print i (stored in res).

2. Step forward. Later values use res = res + k, then k-- so each step is smaller.

3. Row length. The inner loop runs i times (j from i to i+i−1).

Example 2 — Scanner Input

Read rows at runtime. Same stepping logic.

Java
import java.util.Scanner;

public class DiagonalFillNumberTriangleInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter rows: ");
        int rows = sc.nextInt();
        if (rows < 1) return;

        for (int i = 1; i <= rows; i++) {
            int k = rows - 1;
            int res = i;
            for (int j = i; j < i + i; j++) {
                if (i == j) System.out.print(j + " ");
                else {
                    res = res + k;
                    System.out.print(res + " ");
                    k--;
                }
            }
            System.out.println();
        }
        sc.close();
    }
}

How It Works

1. Prompt and guard. Read rows; exit early if it is less than 1.

2. Same math. Only the source of rows changes — k = rows - 1 still resets each row.

3. Safer input tip. Prefer:

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

Example 3 — Compact Rows

Same logic — StringBuilder joins values without a trailing space.

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

        for (int i = 1; i <= rows; i++) {
            int k = rows - 1;
            int res = i;
            StringBuilder row = new StringBuilder();

            for (int j = i; j < i + i; j++) {
                if (row.length() > 0) row.append(" ");
                if (i == j) row.append(j);
                else {
                    res = res + k;
                    row.append(res);
                    k--;
                }
            }
            System.out.println(row);
        }
    }
}

How It Works

1. Same steps. Still start at i and add decreasing k offsets.

2. Cleaner spacing. Append a space only when the builder already has content — no trailing space.

3. Same shape. The triangle of numbers is identical; only end-of-row whitespace differs.

Edge Cases & Pitfalls

Check these before calling the solution done.

Forgot k reset

Wrong later rows

Set k = rows - 1 at the start of every row. Reusing a leftover k breaks the diagonal fill.

Skip k--

Constant steps

Without k--, every step adds the same offset and the triangle no longer matches the classic fill.

Wrong loop

Wrong count

Inner loop must run i times. j from i to i+i−1 (j < i + i) is the usual form.

rows = 1

Single value

Output is just 1.

rows = 0

Empty output

The outer loop never runs. Guard interactive input with rows >= 1.

Bad input

Use hasNextInt

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

Time and Space Complexity

ProgramTimeExtra space
Examples 1–2O(n²)O(1)
StringBuilder (Example 3)O(n²)O(n) per row

Total printed values for n rows: 1 + 2 + … + n = n(n+1)/2.

Key Takeaways

  • Rule: start at i; then res = res + k with k decreasing from rows − 1.
  • Reset: set k = rows - 1 at the start of every row.
  • Length: row i prints exactly i numbers.
  • Complexity: O(n²) prints for n rows.

One line: print i, then keep adding a shrinking step k to fill the diagonal triangle.

Frequently Asked Questions

Row 2 starts at 2 (when i==j). Next value: res=2+4=6 because k starts at rows-1=4.
k starts at rows-1 each row and decreases after each step. It is the offset added to res for the next number.
With 5 rows you print 1+2+3+4+5=15 numbers total — 15 is the final value on the last row.
Yes. Use a variable rows and set k = rows - 1 at the start of each row.
Exactly i numbers — the inner loop runs from j = i to j < i + i.
Build each row with StringBuilder and append spaces only between values — see Example 3.
O(n²) for n rows because you print n(n+1)/2 numbers in total.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you know?

Each row starts with index i, then adds decreasing step sizes via res = res + k where k starts at rows - 1. Row i prints exactly i numbers.

Next: Palindromic Number Pyramid

Continue with the palindromic number pyramid pattern in the Java number-pattern series.

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