Java Number Pattern (Rotating Digits)

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

What Is This Pattern?

A rotating number pattern keeps every row the same length while the start value shifts right and wraps with a descending tail.

Remember
Rule: for i from 1 to rows,
      print i..rows, then print (i-1)..1

12345
23451
34521
45321
54321     ← rows = 5

Unlike Program 38 (shrinking sequential triangle), here every row has exactly rows digits.

How to Solve It

Walk i from 1 to rows; print i..rows, then append i-1..1.

MethodIdeaBest for
Dual inner loopsAscending run i..rows, then descending wrap i-1..1Learning, interviews, exams
Spaced digitsSame loops; print each value with a trailing spaceReadable output when rows > 9

Pseudocode

Pseudocode
for i from 1 to rows:
    for j from i to rows:
        print j
    for k from i down to 2:
        print (k - 1)
    print newline

Cheat sheet

GoalPattern
Walk rowsfor (int i = 1; i <= rows; i++)
Main runfor (int j = i; j <= rows; j++) print(j)
Wrap tailfor (int k = i; k > 1; k--) print(k - 1)
End the rowSystem.out.println();
Digits per rowAlways rows

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.printStays on the same lineEach digit in both inner loops
System.out.printlnEnds the current lineAfter both inner loops finish

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

Live Preview

Change the row count and the rotating pattern 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 · 25 digits
12345
23451
34521
45321
54321

Worked Walkthrough — rows = 5

Trace the main run (i..rows) and the wrap tail (i-1..1) for each row.

iMain runWrap tailPrinted row
11..5(empty)12345
22..5123451
33..52, 134521
44..53, 2, 145321
554 … 154321

Each row has exactly 5 digits — total 5 × 5 = 25.

Java Programs

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

Example 1 — Fixed rows = 5

Hard-coded size — dual inner loops with compact digits.

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

        for (int i = 1; i <= rows; i++) {
            for (int j = i; j <= rows; j++)
                System.out.print(j);
            for (int k = i; k > 1; k--)
                System.out.print(k - 1);
            System.out.println();
        }
    }
}

How It Works

1. Outer loop. i is the start of the main run for that row.

2. Main run. j prints from i up to rows.

3. Wrap tail. k runs from i down to 2 and prints k - 1.

When i = 1: only the main run — 12345. When i = 3: 345 + 21 → 34521.

Example 2 — Rows Input

Read rows at runtime. Same dual-loop core.

Java
import java.util.Scanner;

public class RotatingNumberPatternInput {
    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;

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

How It Works

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

2. Same core. Only the source of rows changes from a literal to user input.

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 — Spaced Output

Same dual loops — each value printed with a trailing space for readability.

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

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

How It Works

1. Same structure. Dual loops unchanged — only the print adds a space.

2. Why space? Digits stay readable when values reach two digits.

3. Width tip. For larger rows, prefer format("%2d ", value) for aligned columns.

Edge Cases & Pitfalls

Check these before calling the solution done.

println inside

Column of digits

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

Skip wrap

No rotation

Omitting the second loop prints only i..rows and loses the wrap-around tail.

Wrong wrap

34512 vs 34521

Appending 1..i-1 ascending gives a pure rotation. This pattern uses descending i-1..1.

No println

One long line

Forgetting println() after the row glues every digit onto one endless line.

rows = 1

Single digit

Output is just 1 on one line — the wrap loop never runs.

Bad input

Use hasNextInt

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

Time and Space Complexity

ProgramTimeExtra space
Rotating pattern (Examples 1–3)O(n²)O(1)

Each of n rows prints n digits — total n². Only loop counters are stored.

Key Takeaways

  • Rule: row i prints i..rows then i-1..1.
  • Fixed width: every row has exactly rows digits.
  • Break the row: call println only after both inner loops.
  • Complexity: O(n²) time; O(1) extra space.

One line: for each row, print i..rows then i-1..1 with print, then println().

Frequently Asked Questions

When i=5 and rows=5, the first loop prints 5, then the second loop appends 4, 3, 2, 1 — giving 54321.
The first loop prints the ascending run from i to rows. The second appends the wrap-around tail from i-1 down to 1.
Program 38 prints one continuous sequence with shrinking row widths. Program 39 keeps every row at rows digits by wrapping back to smaller numbers.
No. A pure rotation would give 34512 on row 3. This pattern prints i..rows then (i-1)..1, so row 3 is 34521.
Yes. Print j + " " and (k-1) + " " in the loops — see Example 3.
O(n²) where n is rows. Each of n rows prints n digits.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you know?

Each row prints i..rows then i-1..1 — two inner loops that create the rotation. Every row has exactly rows digits, so total output is n² for n rows.

Next: Alternating 1/0 Pattern

Move on to the alternating ones-and-zeros pattern in the Java number-pattern series.

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