Java Alternating Number Triangle Pattern (Zigzag)

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

What Is This Pattern?

An alternating zigzag number triangle shrinks from rows to 1, printing ascending digits on odd lengths and descending digits on even lengths.

Remember
Rule: outer i = rows..1;
      odd i → print 1..i; even i → print i..1

12345
4321
123
21
1          ← rows = 5

Unlike Program 1 (always 1..i) or Program 12 (repeating digits), this pattern flips direction with i % 2 while the row length shrinks.

How to Solve It

Outer loop from rows down to 1. If i is even, print i..1; otherwise print 1..i. End the line after the inner loop.

MethodIdeaBest for
if / elseTwo inner loops chosen by i % 2Learning, interviews, exams
start / end / stepOne inner loop with computed boundsCompact dry-runs

Pseudocode

Pseudocode
for i from rows down to 1:
    if i is even:
        for j from i down to 1:
            print j
    else:
        for j from 1 to i:
            print j
    print newline

Cheat sheet

GoalPattern
Outer (shrink)for (int i = rows; i >= 1; i--)
Odd lengthfor (int j = 1; j <= i; j++) System.out.print(j);
Even lengthfor (int j = i; j >= 1; j--) System.out.print(j);
Pick branchif (i % 2 == 0) { ... } else { ... }
End the rowSystem.out.println();
One-loop formSet start, end, step from parity

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.printStays on the same lineEach digit j
System.out.printlnEnds the current lineAfter the inner loop

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

Live Preview

Change the row count and the zigzag triangle updates instantly.

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

Live result rows = 5 · 15 digits
12345
4321
123
21
1

Worked Walkthrough

Trace three outer values when rows = 5 — watch parity flip the print direction.

Outer iParityInner jPrints
5odd1..512345
4even4..14321
3odd1..3123

Row length is always i; only the travel direction of j changes with parity.

Java Programs

Three complete programs: fixed rows = 5, Scanner input, and a start/end/step one-loop form. Use View Output to reveal sample results.

Example 1 — Fixed rows = 5

Hard-coded height — outer down from 5, if/else picks ascending or descending.

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

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

How It Works

1. Outer shrinks the length. i starts at rows and moves toward 1 — that is how many digits each row gets.

2. Parity picks the direction. Even i prints i..1; odd i prints 1..i.

3. End the row. Call System.out.println() only after the chosen inner loop finishes.

Example 2 — User Input Rows

Read the row count at runtime. Prefer hasNextInt() before nextInt() in real apps.

Java
import java.util.Scanner;

public class ZigzagNumberTriangleInput {
    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 = rows; i >= 1; i--) {
            if (i % 2 == 0) {
                for (int j = i; j >= 1; j--) {
                    System.out.print(j);
                }
            } else {
                for (int j = 1; j <= i; j++) {
                    System.out.print(j);
                }
            }
            System.out.println();
        }
        sc.close();
    }
}

How It Works

1. Same loop core. Only the source of rows changes from a literal to Scanner.

2. Entering 4 starts even. The first row is length 4, so it opens with 4321.

3. Validate in real apps. Prefer checking hasNextInt() and requiring a positive height (tip below).

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

Example 3 — start / end / step

One inner loop — compute direction up front from parity.

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

        for (int i = rows; i >= 1; i--) {
            int start = (i % 2 == 0) ? i : 1;
            int end = (i % 2 == 0) ? 1 : i;
            int step = (i % 2 == 0) ? -1 : 1;

            for (int j = start; step > 0 ? j <= end : j >= end; j += step) {
                System.out.print(j);
            }
            System.out.println();
        }
    }
}

How It Works

1. Same zigzag rule. Odd lengths still climb; even lengths still fall.

2. Bounds replace the branch. start, end, and step encode the two if/else loops in one place.

3. Learn the branch first. Prefer Examples 1–2 in class; use this form once the parity rule is clear.

Edge Cases & Pitfalls

Check these before calling the solution done.

Parity

Test i % 2, not the row index from the top

Direction depends on the current length i. When rows is even, the first row is descending.

Swapped branches

Even must print i..1

Swapping the branches flips the zigzag and no longer matches 12345 / 4321.

println inside

Do not put println inside the inner loop

That prints one digit per line and destroys the triangle.

Bad input

Validate with hasNextInt

nextInt() throws on letters — prefer hasNextInt() and require rows >= 1.

Time and Space Complexity

ProgramTimeExtra space
if / else (Examples 1–2)O(n²)O(1)
start / end / step (Example 3)O(n²)O(1)

Digits printed are n + (n − 1) + … + 1 = n(n + 1) / 2 — quadratic in n. Extra memory is only the loop variables.

Key Takeaways

  • Rule: outer i = rows..1; odd → 1..i, even → i..1.
  • Flip: i % 2 chooses direction; length still shrinks every row.
  • Break the row: call println only after the inner loop finishes.
  • Complexity: O(n²) time, O(1) extra space.

One line: shrink the row, then let parity decide whether digits climb or fall.

Frequently Asked Questions

An alternating zigzag number triangle: for rows=5 you get 12345, 4321, 123, 21, 1.
That row has length i = 4, which is even. The even branch runs j from i down to 1 and prints 4, 3, 2, 1.
System.out.print(j) stays on the same line. System.out.println() ends the current line. Digits use print; the row break uses println after the inner loop.
Program 12 repeats the row digit (11111, 2222, 333). Program 13 prints sequential digits 1..i or i..1 and flips direction with i % 2.
Program 1 always prints 1..i while shrinking. Program 13 also shrinks, but even lengths reverse to i..1.
Yes. Compute start, end, and step from i % 2, then use one for loop — see Example 3.
O(n²) for n rows because total prints are 1 + 2 + ... + n = n(n+1)/2.
One row prints a single digit 1.

Did you know?

Odd row length i prints 1..i; even row length prints i..1. The outer loop shrinks from rows to 1, and i % 2 flips direction — still O(n²) total digit prints.

Next: Odd-Length Descending Triangle

Continue with the next pattern in the Java number-pattern series.

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