Java Number Triangle Pattern (Alternating Direction)

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

What Is This Pattern?

An alternating ascending/descending triangle fills numbers from 1 continuously, but flips print direction each row — odd rows ascend, even rows descend.

Remember
Rule: k starts at 1
      for each row i: m = k + i - 1
        odd i  → print k upward
        even i → print m downward
      always k++ after each value

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

Unlike Program 50 (fixed digits with dual loops), here a running counter k drives Floyd-style filling with alternating direction.

How to Solve It

Keep a running counter k. For each row, compute the end m, then print ascending or descending by parity.

MethodIdeaBest for
Fixed rowsHard-code rows; k/m logicLabs and demos
Scanner inputSame logic; read rows at runtimeInteractive practice
No trailing spaceSpace before 2nd+ values onlyCleaner row formatting

Pseudocode

Pseudocode
k = 1
for i from 1 to rows:
    m = k + i - 1
    for j from 1 to i:
        if i is odd: print k
        else: print m; m = m - 1
        k = k + 1
    new line

Cheat sheet

GoalPattern
Start counterint k = 1;
Row endint m = k + i - 1;
Odd rowSystem.out.print(k + " ");
Even rowSystem.out.print(m-- + " ");
Advancek++; after every printed value

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.printStays on the same lineEach value 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 alternating triangle updates instantly.

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

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

Worked Walkthrough — rows = 5

Trace k, m, and row parity for each line.

iStart kmDirectionPrinted row
111odd ↑1
223even ↓3 2
346odd ↑4 5 6
4710even ↓10 9 8 7
51115odd ↑11 12 13 14 15

Always increment k after each print — even on even rows where you display m.

Java Programs

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

Example 1 — Fixed rows = 5

Hard-coded size — compute m = k + i - 1 and alternate print direction by row parity.

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

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

How It Works

1. Running counter. k is the next number in sequence and never resets between rows.

2. Row end. m = k + i - 1 is the last value that belongs on this row.

3. Direction. Odd rows print k ascending; even rows print m downward. Always k++ after each value.

Example 2 — Scanner Input

Read rows at runtime. Same k/m logic.

Java
import java.util.Scanner;

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

        int k = 1;
        for (int i = 1; i <= rows; i++) {
            int m = k + i - 1;
            for (int j = 1; j <= i; j++) {
                if (i % 2 == 1) System.out.print(k + " ");
                else System.out.print(m-- + " ");
                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 logic. Only the source of rows changes — the counter and parity rules are identical.

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 — No Trailing Space

Same counter logic — space only before the second and later values on each row.

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

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

How It Works

1. Same math. Still use m = k + i - 1 and odd/even direction.

2. Smarter spacing. if (j > 1) adds a space before later values — no trailing space after the last number.

3. Same shape. The triangle looks identical; only the end-of-row whitespace is cleaner.

Edge Cases & Pitfalls

Check these before calling the solution done.

Forgot k++

Stuck numbers

If you skip k++ on even rows, later rows reuse the wrong range. Always increment after every print.

Wrong m

Broken reverse

Use m = k + i - 1. Starting from k alone on even rows prints ascending instead of descending.

Reset k

Not continuous

Resetting k each row breaks the continuous fill — numbers must keep climbing across the whole triangle.

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
All three examplesO(n²)O(1)

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

Key Takeaways

  • Rule: continuous k; odd rows print k, even rows print m downward.
  • Row end: m = k + i - 1 before the inner loop.
  • Always: k++ after every printed value — even on descending rows.
  • Complexity: O(n²) prints for n rows.

One line: fill with k; odd rows go up, even rows go down from m.

Frequently Asked Questions

Row 2 is even, so values 2 and 3 are printed in reverse order as 3 2.
If k is the next number to print, row i contains i values ending at m = k + i - 1.
Row 4 starts at k=7, so m=10. Even rows print m downward: 10, 9, 8, 7.
Yes. Use a variable rows in the outer loop — the same k/m logic works for any positive n.
Print a space only before the second and later values — see Example 3.
No. k is a running counter that continues across all rows.
O(n²) for n rows. Total prints are 1+2+...+n = n(n+1)/2.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you know?

Numbers fill continuously from 1, but each row alternates print direction — odd rows ascending (4 5 6), even rows descending (10 9 8 7). Compute row end with m = k + i - 1.

Next: Increasing-Decreasing Palindrome Pattern

Continue with the increasing-decreasing palindrome pattern in the Java number-pattern series.

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