Rotating Number Pattern in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Dual Inner Loops

What You’ll Learn

The rotating number pattern shifts the starting digit each row while keeping fixed width. This tutorial covers the two-part row rule, dual inner loops, a live preview, algorithm steps, worked Java examples, edge cases, and complexity.

Shape Rule

Fixed width, rotating start

Every row prints exactly rows digits; the starting value shifts from 1 up to rows.

Part 1 Loop

i..rows

for (j = i; j <= rows; j++) prints the ascending run like 2345.

Part 2 Loop

Wrap-around tail

for (k = i; k > 1; k--) appends k-1 to complete the row.

Outer Loop

Row start i

for (i = 1; i <= rows; i++) shifts the rotation each line.

Live Preview

1–20 rows

Pick a row count and draw the rotating pattern instantly in the browser.

O(n²)

Complexity

Total digits = n × n; extra memory stays O(1).

Introduction

A rotating number pattern keeps every row the same length while the sequence wraps around. With rows = 5, the output is 12345, 23451, 34521, 45321, and 54321.

In Java you solve it with one outer loop and two inner loops per row: print i..rows, append i-1..1, then call System.out.println() to move to the next line.

Why it matters?

It teaches dual inner loops on the same row — a key step before wrap-around and cyclic patterns.

Key Highlights

Two Parts Per Row

Part 1: i..rows; Part 2: i-1..1.

Fixed Row Width

Every row prints exactly rows digits.

Print Then Break

System.out.print(j) in both inner loops; println() after.

Series Foundation

Follow Program 38 sequential triangle; continue to Program 40 alternating 1/0.

In short: for each row i from 1 to rows, print i..rows then i-1..1, then call System.out.println().

📝 Problem & Approach

Given a positive integer rows, print consecutive integers starting at 1 in a triangle where row i contains exactly rows - i + 1 values.

Java
// First 5 rows (conceptual shape)
//   1  2  3  4  5
//   6  7  8  9
//  10 11 12
//  13 14
//  15

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle lines to print (typically ≥ 1).
Printed outputtextLeft-aligned rows of consecutive integers; row i has rows - i + 1 values.

Minimal workflow

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

Approach comparison

ApproachIdeaBest for
Dual inner loops per row Outer row + two inner parts Learning and interviews
Spaced / formatted outputAdd spaces or %2d between digitsReadability for rows > 9

⚡ Quick Reference

GoalPattern
Walk each rowfor (i = 1; i <= rows; i++)
Print ascending runfor (j = i; j <= rows; j++) System.out.print(j);
Append wrap-aroundfor (k = i; k > 1; k--) System.out.print(k - 1);
End the rowSystem.out.println();
Program 38 variantShrinking width with global k counter instead of rotation

📋 Part 1 vs Part 2 vs Combined

Same rotating row — the two inner loops and their roles.

Part 1 (ascending)
i..rows

Prints 2345 when i = 2 and rows = 5

Part 2 (wrap)
i-1..1

Appends 1 to complete 23451

Row length
always n

Both parts together always print rows digits

Learning tip
trace i=2

Dry-run one row before coding the full pattern

Context

When This Pattern Shows Up

Reach for this pattern when teaching two inner loops on the same row.

  1. First lab exercise

    Most Java pattern series start here before pyramids and diamonds.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with Scanner for a flexible row count.

  4. Gateway to variants

    Compare Program 38 sequential triangle and Program 40 alternating 1/0 next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 1 and 20 and draw the rotating number pattern in the browser.

Try 5, 7, or 10. Larger values still work up to 20.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed row count, Scanner input, and a spaced-output variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with dual inner loops per line.

Example 1 — Fixed rows = 5

Hard-coded size — two inner loops build each rotating row.

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

When i = 2, the first loop prints 2345 and the second appends 1, giving 23451. When i = 5, the first loop prints 5 and the second appends 4321, giving 54321.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read the maximum digit with Scanner.nextInt() (check hasNextInt() in real apps).

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 maximum number: ");
        int rows = sc.nextInt();

        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

Same dual-loop core as Example 1; only the source of rows changes. Non-numeric input throws InputMismatchException with nextInt() — check hasNextInt() for safer labs.

⚡ Readability Variant

Same rotation with spaces between digits for easier reading.

Example 3 — Spaced Output

Append a space after each digit so multi-digit rows stay readable.

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

Same loop structure; only the print calls add + " " after each digit. Essential when rows exceeds 9 or when demonstrating output formatting.

🧠 How the Algorithm Prints Rows

1

Set up

System.out is built in; use Scanner when reading input. Set rows (fixed or from input).

Setup
2

Outer loop (rows)

for (i = 1; i <= rows; i++) picks the starting digit for each rotating row.

Row
3

Inner loop 1 (ascending)

for (j = i; j <= rows; j++) prints the main run with System.out.print(j).

Part 1
4

Inner loop 2 (wrap)

for (k = i; k > 1; k--) appends k-1, then println() ends the row.

Part 2
=

Triangle complete

Total digit prints: n × nO(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 4

Trace each row: part 1 (i..rows) plus part 2 (i-1..1).

iPart 1Part 2Full row
112341234
223412341
334213421
443214321

Total digit prints: 4 × 4 = 16 = .

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change j <= i and watch the shape change.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: change k start to 100 for a shifted sequence.

3. Console Formatting Drills

Practice System.out.print vs row newline without complex math.

Example: put System.out.println() inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: use %4d when values exceed two digits.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed digits for n = 10 still → 55.

6. Input Validation Labs

Pair the pattern with Scanner and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner Java courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the two-loop row version first; then try spaced output for larger rows.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use rows (or n) and keep i/j for row/column — or rename to row/col.

  2. 2. Prefer Scanner

    Avoid crashes when the user types letters instead of a number.

  3. 3. Keep System.out.println() Outside

    Only call System.out.println() after the inner loop finishes the row.

  4. 4. Pick Field Width Early

    Add spaces or %2d when rows exceeds 9.

  5. 5. Dry-Run One Small n

    Trace rows = 3 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put System.out.println() inside the inner loop.

Common Pitfalls

Mistakes that commonly break rotating number patterns.

  1. 1. System.out.println() Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use System.out.print(j) and System.out.print(k-1); println() only after both inner loops.

  2. 2. Wrong Inner Bound

    Using Skipping the second inner loop leaves rows short — e.g. 2345 instead of 23451.

    → Run both loops: j = i..rows then k = i..2 printing k-1.

  3. 3. Forgetting the Row Break

    Omitting System.out.println() glues every digit onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Unchecked Scanner input

    Letters or empty input throw undefined rows.

    → Prefer Scanner and re-prompt on failure.

  5. 5. Off-by-One on 0-Based Loops

    Switching to i = 0 without adjusting the inner bound prints an empty first row or wrong counts.

    → If 0-based, print i with wrong inner bound (e.g. j <= i + 1).

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single digit

Output is just 1 on one line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Many rows

Output grows as n²/2 characters — fine for labs, noisy for huge n.

Bad input

Non-numeric Scanner input

Unchecked Scanner leaves rows unset — call sc.hasNextInt() first.

Fill char

Alphabet rotation

Try alphabet rotation (A..E) using the same two-loop structure.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Sequential decreasing triangle

  • Global k counter with shrinking rows
  • Review Program 38

2. Alternating 1/0 pattern

  • Odd rows print 1, even rows print 0
  • Continue with Program 40

3. Reverse rotation

  • Start outer loop from rows down to 1
  • Watch how the starting digit shifts backward

4. Spaced output

  • Add spaces between digits for rows > 9
  • See Example 3 on this page

Notes

  • Square count. Total digit prints for n rows is — every row has n digits.
  • print stays on the line; println advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • This page is left-aligned. Centered pyramids need leading spaces — covered later in the series.

Quick Takeaway: outer loop picks start i, two inner loops build the row, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
Spaced output (Example 3)O(rows²)O(1)
Wrap Up

🎉 Conclusion

The rotating number pattern combines one outer loop with two inner loops per row — a natural step after sequential triangles. Master the compact digit output first, then optionally add spaces for readability.

Practice the three examples above, then continue to Program 40 for the alternating 1/0 pattern.

Row i prints i..rows then i-1..1 — keep println() only after both inner loops finish.

💡 Best Practices

✅ Do

  • Explain part 1 (i..rows) and part 2 (i-1..1) before coding
  • Use System.out.print in both inner loops and println() after each row
  • Validate rows ≥ 1 for interactive programs
  • Check Scanner return value before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call System.out.println() inside the inner digit loop
  • Skip the second inner loop (rows come out too short)
  • Skip the newline after each row
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this rotating pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Controls each row

Code
2 03

Two inner loops

Part 1 + Part 2 per row

Logic
n 04

Fixed width

n digits every row

I/O
O 05

Complexity

O(n²) time

Analysis

❓ 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.
Yes. Print j + " " and (k-1) + " " in the loops, or build each row with StringBuilder.
Yes, but digits run together without separators. Use spaces or %2d formatting for readability.
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 for n rows.

Continue to Program 40

Move on to the alternating 1/0 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