Diagonal Mirror Number Pattern in Java

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

What You’ll Learn

The diagonal mirror pattern prints numbers on the main diagonal and mirror diagonal with spaces elsewhere — forming an X shape. For n = 5: 1 1, 2 2, 3 3. This tutorial covers i==j and i==k logic, live preview, worked Java examples, edge cases, and O(n²) complexity.

Main Diagonal

i == j

Left loop prints digit j when row i equals column j.

Mirror Diagonal

i == k

Right loop prints digit k when i == k; runs k = n-1..1.

Space Fill

else " "

All non-diagonal positions print a space — only two digits per row (except overlap).

Fixed Width

2n - 1 cells

Each row has exactly 2n-1 character positions for size n.

Live Preview

3–12 for n

Pick a size n and draw the diagonal mirror pattern instantly in the browser.

O(n²)

Complexity

Each row checks 2n-1 cells — total work grows as n².

Introduction

A diagonal mirror number pattern places digits only on the main diagonal (i == j) and mirror diagonal (i == k). Row 1 shows 1 1; row 3 shows digits at both X arms.

In Java: outer for (i = 1; i <= n; i++), inner for (j = 1; j <= n; j++) print digit or space, inner for (k = n-1; k >= 1; k--) print digit or space, then println() after both halves.

Why it matters?

It is a nested-loop exercise that places digits only on the main and mirror diagonals.

Key Highlights

Outer loop i

i = 1..n picks each row number.

Main + mirror

Left loop prints when i==j; mirror loop prints when i==k.

Two Diagonal Loops

Two loops per row — main diagonal half, then mirror diagonal half.

Series Foundation

Follow Program 52 palindrome rows; continue to Program 54 diamond diagonal.

In short: outer i=1..n, inner j=1..n with i==j, inner k=n-1..1 with i==k, then println().

📝 Problem & Approach

Given n = 5, print five lines with digits on both diagonals and spaces elsewhere.

Java
// n = 5 (conceptual output)
// 1       1
//  2     2 
//   3   3  
//    4 4   
//     5    

Inputs & Outputs

ItemTypeDescription
nintPattern size — number of rows and diagonal width (typically ≥ 1).
i, jintRow index i; column j for main diagonal, column k for mirror diagonal.
Printed outputtext2n-1 cells per row — fixed width for size n.

Minimal workflow

Pseudocode
for i from 1 to n:
    for j from 1 to n: print j if i==j else space
    for k from n-1 down to 1: print k if i==k else space
    newline

Approach comparison

ApproachIdeaBest for
Two diagonal loopsif (i==j) print(j) else print(" "); mirror loop with i==kFixed width — 2n-1 cells per row
Scanner inputsc.nextInt() for nUser-chosen pattern size
Star diagonalsPrint * on diagonals instead of numbersVisual X-shape without digits — Example 3

⚡ Quick Reference

GoalPattern
Set sizeint n = 5;
Outer loopfor (i = 1; i <= n; i++)
Main diagonalfor (j = 1; j <= n; j++) — print when i == j
Mirror diagonalfor (k = n-1; k >= 1; k--) — print when i == k
Non-diagonal cellSystem.out.print(" ");
Row breakSystem.out.println(); after both halves
Program 52 contrastPalindrome rows use increase/decrease loops; this pattern uses i==j and i==k diagonal checks

📋 Main Diagonal vs Mirror Diagonal vs Combined

How outer row selection, main diagonal loop, mirror diagonal loop, and row breaks work together.

Outer loop
for (i = 1; i <= n; i++)

Picks row number i — also the diagonal digit value.

Main diagonal
for (j = 1; j <= n; j++)
  if (i == j) print(j)
  else print(" ")

Prints digit at column j when i == j.

Mirror diagonal
for (k = n-1; k >= 1; k--)
  if (i == k) print(k)
  else print(" ")

Prints digit when i == k; loop starts at n-1.

Learning tip
trace i=3, n=5

Dry-run row 3 — digits at both diagonal positions: 3 3.

Context

When This Pattern Shows Up

Reach for this pattern when teaching nested loops, diagonal conditions, and fixed-width row output.

  1. First lab exercise

    Classic follow-up after palindrome row patterns like Program 52.

  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 pattern size.

  4. Gateway to variants

    Compare with Program 52 (palindrome rows), then continue to Program 54 (diamond diagonal).

  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 i==j, i==k, mirror bounds, and O(n²) thinking.

🔮 Live Preview

Choose pattern size n and draw the diagonal mirror number pattern in the browser.

Try 3, 5, or 8 for n (up to 12).

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed n = 5, Scanner input, and a star-diagonal variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with digits on main and mirror diagonals — X-shaped output.

Example 1 — Fixed n = 5

Hard-coded size — left loop with i==j, mirror loop with i==k.

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

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

How It Works

When i = 3 and n = 5, the main diagonal prints 3 at column 3; the mirror diagonal also prints 3. Row 1 prints 1 on both diagonals — 1 1.

📈 Practical Variant

Read n with Scanner for flexible output size.

Example 2 — Scanner Input

Same diagonal conditions; size n comes from user input.

Java
import java.util.Scanner;

public class DiagonalMirrorNumberPatternInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = sc.nextInt();

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

        sc.close();
    }
}

How It Works

Identical diagonal logic to Example 1; only the size is dynamic.

⚡ Character Variant

Print * on diagonals instead of row numbers.

Example 3 — Star Diagonals

Replace digits with * when i==j or i==k.

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

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

How It Works

Same diagonal logic; only the printed character changes from digit to *.

🧠 How the Algorithm Prints Rows

1

Set up

System.out is built in; use Scanner when reading input. Set n (e.g. 5).

Setup
2

Loop rows

for (i = 1; i <= n; i++) — one iteration per output line.

Loop
3

Main and mirror halves

Left loop: print digit when i==j, else space. Mirror loop: print when i==k for k = n-1..1.

Diagonals
4

New line after row

System.out.println(); after both inner loops moves to the next row.

Break
=

Diagonal mirror pattern complete

Total checks = n(2n-1)O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — row i = 3, n = 5

Trace row 3 to see how main and mirror diagonal checks place digits at both X arms.

HalfCondition hitRow so far
Left (j=1..2)no match  
Left (j=3)i==j → print 3  3
Left (j=4,5)spaces  3  
Mirror (k=4,5)spaces  3   
Mirror (k=3)i==k → print 3  3  3
Mirror (k=2,1)spaces  3  3  

Final row: 3 3. Then println() moves to the next row.

Use Cases

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

1. Teaching Two Diagonal Loops

Clearest visual proof that outer and inner bounds interact.

Example: use Scanner for dynamic n — see Example 2.

2. Mirror Loop Bounds

Mirror loop runs k = n-1 down to 1 so the center column is not duplicated.

Example: compare row 3 with n=5 — digits at columns 3 and 3 on main and mirror diagonals.

3. Console Formatting Drills

Practice println vs print for multi-line vs single-line output.

Example: use print("*") when i==j or i==k — see Example 3.

4. Star Diagonals

Print * when i==j or i==k instead of the row number.

Example: print n=5 with * on diagonals and compare the X shape.

5. Complexity Intuition

Fixed width 2n-1 makes O(n²) concrete for beginners.

Example: count cells for n=5 → 5 rows × 9 cells = 45 prints.

6. Input Validation Labs

Pair the pattern with Scanner and positive-row checks.

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

Pro Tip: when an interviewer asks for patterns, explain the outer/inner loop 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 mirror loop start shows immediately — center column may print twice.

  2. 2. Minimal Concepts

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

  3. 3. Easy to Extend

    Change n, use Scanner, or print * on diagonals instead of numbers.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the i==j and i==k conditions first; then try Scanner input and the star variant in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Variables Clearly

    Use n for pattern size and i/j/k for row/column indices.

  2. 2. Prefer Scanner

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

  3. 3. Row Break After Inner Loop

    Run left diagonal loop, run mirror loop, then println().

  4. 4. Use print for Diagonal Cells

    Use print(j) or print(" ") in the main loop; same for the mirror loop; one println() per row after both halves.

  5. 5. Dry-Run One Small n

    Trace n = 5, i = 3 on paper — expect digits at both diagonal positions.

Pro Tip: if the center column prints twice, check whether the mirror loop starts at n instead of n-1.

Common Pitfalls

Mistakes that commonly break diagonal mirror number patterns.

  1. 1. println() Inside an Inner Loop

    Each cell lands on its own line — you get a column, not an X-shaped row.

    → Use print inside both inner loops; println() only after they finish.

  2. 2. Mirror Loop Starts at n

    Starting at k = n duplicates the center column — row 3 shows two middle digits instead of one spaced pair.

    → Start the mirror loop at k = n - 1 and count down to 1.

  3. 3. Forgetting the Row Break

    Omitting println() after both inner loops glues all rows onto one line.

    → Always call System.out.println() after both diagonal loops complete.

  4. 4. Wrong Condition in Mirror Loop

    Using i == j in the mirror loop prints digits on the wrong diagonal.

    → Main loop uses i == j; mirror loop uses i == k.

  5. 5. Unchecked Scanner Input

    Letters or empty input throw InputMismatchException.

    → Use sc.hasNextInt() before sc.nextInt().

  6. 6. Hard-coding 5 Everywhere

    Using literal 5 in loop bounds instead of variable n breaks dynamic input.

    → Use one n variable for both inner loop bounds.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single line

Output is one line: 1 — mirror loop does not run.

n = 0

Empty pattern

Loop never runs — print nothing or show a message.

Negative

n < 0

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

Large n

Large n

Large values produce wide rows — fine for labs; use smaller n for quick demos.

Bad input

Non-numeric Scanner input

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

Compact

Single-line form

Use conditional spacing to avoid trailing spaces — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change n

  • Try n = 3, 6, or 8
  • Verify digits appear only on i==j and i==k positions

2. Star diagonals

  • Print * instead of numbers on diagonals
  • Compare number X vs star X output

3. Mirror bounds

  • Try mirror loop k = n..1 instead of n-1..1
  • Observe center-column duplication

4. Next in series

  • Continue with Program 54 diamond diagonal
  • Connect to diamond diagonal patterns

Notes

  • Cell count. Total checks ≈ n(2n-1) (e.g. 45 cells for n=5).
  • print stays on the line; println advances — mix them carefully.
  • Validate n > 0 for interactive programs; n = 1 prints a single digit.
  • Main diagonal: if (i==j) print(j) else print(" "); mirror: if (i==k) print(k) else print(" ").

Quick Takeaway: outer i=1..n, inner j=1..n with i==j, inner k=n-1..1 with i==k, then println().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Fixed n = 5 (Example 1)O(n²)O(1)
Scanner input (Example 2)O(n²)O(1)
Star diagonals (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The diagonal mirror pattern combines nested loops with diagonal conditions — a natural step after palindrome row patterns. Master the fixed-n version first, then try Scanner input and the star-diagonal variant in Example 3.

Practice the three examples above, then continue to Program 54 for the diamond diagonal number pattern.

Keep println() after both diagonal halves — one row break per outer iteration.

💡 Best Practices

✅ Do

  • Explain outer i, main diagonal i == j, and mirror diagonal i == k before coding
  • Use print(j) or print(" ") in left loop; same for mirror loop; then println()
  • Validate n ≥ 1 for interactive programs
  • Check Scanner return value before using n
  • State O(n²) time when asked about complexity

❌ Don’t

  • Start mirror loop at k = n (duplicates center)
  • Use i == j in the mirror loop by mistake
  • Hard-code 5 instead of variable n
  • Ignore bad console input in user-facing demos
  • Skip the n = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this diagonal mirror pattern

Print digits only where the main and mirror diagonals cross each row.

5
Core concepts
02

Outer loop

i = 1..n

Code
03

Diagonal checks

Main: i==j; mirror: i==k

Logic
n 04

Fixed width

2n-1 cells/row

I/O
O 05

Complexity

O(n²)

Analysis

❓ Frequently Asked Questions

For i=1, i==j prints 1 on the main diagonal and i==k prints 1 on the mirror diagonal when k=1.
At i=n, both diagonals meet at the same position in the left half, so only one digit appears.
Starting at n would duplicate the center column. k = n-1 down to 1 mirrors without repeating the middle.
Yes. Use a variable n — both inner loops run with the same diagonal conditions.
Replace the printed digit with * when i==j or i==k — see Example 3.
Each row has 2n-1 character positions — n for the left half and n-1 for the mirror half.
O(n²) for n rows. Each row checks O(n) cells in two loops.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you Know? 🔊

Row i prints the number on the main diagonal (i == j) and on the mirror diagonal (i == k). All other cells are spaces — an X-shaped number pattern.

Continue to Program 54

Move on to the diamond diagonal number pattern in the Java number-pattern series.

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