Java Diagonal Mirror Number Pattern

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

What Is This Pattern?

A diagonal mirror number pattern prints digits only on the main diagonal (i == j) and the mirror diagonal (i == k). Everywhere else is a space — an X shape.

Remember
Rule: for i = 1..n
        left:  if i==j print j else space
        mirror: if i==k print k else space  (k = n-1..1)

1       1
 2     2 
  3   3  
   4 4   
    5         ← n = 5

Unlike Program 52 (palindrome digit runs), here most cells are spaces — only the two diagonals carry values.

How to Solve It

For each row, walk the left half with i==j, then the mirror half with i==k.

MethodIdeaBest for
Fixed nHard-code size; i==j / i==kLabs and demos
Scanner inputSame logic; read n at runtimeInteractive practice
Star diagonalsPrint * instead of the digitVisual X-shape practice

Pseudocode

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

Cheat sheet

GoalPattern
Set sizeint n = 5;
Main diagonalif (i == j) print(j); else print(" ");
Mirror halffor (int k = n - 1; k >= 1; k--)
Mirror hitif (i == k) print(k); else print(" ");
End rowSystem.out.println();

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.printStays on the same lineEach digit or space in both halves
System.out.printlnEnds the lineAfter both halves finish

Build the full row with print, then break once.

Live Preview

Change n and the diagonal mirror pattern updates instantly.

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

Live result n = 5 · width = 9
1       1
 2     2 
  3   3  
   4 4   
    5    

Worked Walkthrough — n = 5

Trace where each digit lands on the main and mirror diagonals.

iMain (j)Mirror (k)Printed row
1j=1 → 1k=1 → 11 1
2j=2 → 2k=2 → 22 2
3j=3 → 3k=3 → 33 3
4j=4 → 4k=4 → 44 4
5j=5 → 5(none)5

Row 5 has no mirror hit because k only goes down to 1 from n−1 — the diagonals already meet in the left half.

Java Programs

Three complete programs: fixed n = 5, Scanner input, and star diagonals. Use View Output to reveal sample results.

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

1. Left half. Columns j = 1..n — print j only when i == j (main diagonal).

2. Mirror half. Columns k = n−1..1 — print k only when i == k (mirror diagonal).

3. Spaces elsewhere. Every other cell is a space, so the digits form an X.

Example 2 — Scanner Input

Read n at runtime. Same diagonal conditions.

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();
        if (n < 1) return;

        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

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

2. Same logic. Ternary i == j ? j : " " is just a shorter form of the if/else in Example 1.

3. Safer input tip. Prefer:

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

Example 3 — Star Diagonals

Same X-shape — print * instead of the diagonal digit.

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

1. Same positions. Still use i == j and i == k to choose which cells light up.

2. Different glyph. Print * instead of j or k — the X shape stays the same.

3. Same width. Each row is still 2n − 1 characters.

Edge Cases & Pitfalls

Check these before calling the solution done.

k from n

Doubled center

Starting the mirror loop at k = n reprints the middle column. Always start at n − 1.

print(i)

Wrong digit

Print j or k (the column), not i, so both arms show matching numbers on each row.

Missing spaces

Collapsed X

Skipping the else print(" ") branch packs digits together and destroys the diagonal shape.

n = 1

Single digit

Output is just 1 — the mirror loop does not run.

n = 0

Empty output

The outer loop never runs. Guard interactive input with n >= 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)

Each of n rows prints 2n − 1 characters → about 2n² prints.

Key Takeaways

  • Rule: print on i==j (left) and i==k (mirror); spaces everywhere else.
  • Mirror start: k = n − 1 avoids duplicating the center column.
  • Width: each row is 2n − 1 characters.
  • Complexity: O(n²) for size n.

One line: light up i==j and i==k; fill the rest with spaces for an X.

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. The mirror loop starts at n-1 and never matches i=n.
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.

Next: Diamond Diagonal Number Pattern

Continue with 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