Mirror Diagonal Number Pattern in C#

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Conditions

What You’ll Learn

Program 53 prints a mirror diagonal number pattern: each row shows the row number on the main diagonal (left) and on a mirrored diagonal (right), forming a symmetric V-shape — a natural step after Program 52’s palindromic pyramid. This tutorial covers two inner loops with i == j and i == k conditions, a live preview, worked C# examples, edge cases, and complexity.

Shape Rule

Mirrored diagonals

Row i prints i on the main diagonal and again on the mirrored diagonal — spaces fill every other column.

Outer Loop

i = 1..rows

for (i = 1; i <= rows; i++) picks the current row index.

Left Half

j = 1..rows

Console.Write(i == j ? j.ToString() : " ") — print the digit only on the main diagonal.

Right Half

k = rows-1..1

Console.Write(i == k ? k.ToString() : " ") — mirrored diagonal; skipping the center column avoids duplication.

Live Preview

rows = 3..9

Pick row count and draw the V-shaped mirror diagonal pattern in the browser.

O(n²)

Complexity

Each row prints about 2n-1 characters — total work grows as O(n²).

Introduction

A mirror diagonal number pattern prints row i with the digit i on the main diagonal and again on a mirrored diagonal — spaces fill the gaps to form a V-shape. With rows = 5, you get 1 1, 2 2, 3 3, 4 4, 5.

In C# use an outer loop for rows, then two inner loops: left half with i == j, right mirrored half with i == k, printing spaces elsewhere before WriteLine().

Why it matters?

It bridges Program 52’s palindromic rows to conditional diagonal placement — combining nested loops with i == j logic.

Key Highlights

Left diagonal

i == j prints the row digit on the main diagonal.

Right diagonal

i == k mirrors the digit on the opposite diagonal.

vs Program 52

Program 52 uses m++/m-- for palindromic rows; Program 53 uses spacing and conditions.

Series Foundation

Follow Program 52; continue to Program 54 next.

In short: outer i = 1..rows, left loop j = 1..rows with i == j, right loop k = rows-1..1 with i == k, else space, then WriteLine().

📝 Problem & Approach

Given row count rows = 5, print a mirror diagonal number pattern — row i shows digit i on both diagonals with spaces between.

C#
// rows = 5
//1       1
// 2     2
//  3   3
//   4 4
//    5

Inputs & Outputs

ItemTypeDescription
rowsintHow many V-shaped rows to print.
i (outer)intCurrent row index — runs from 1 to rows.
j (left)intScans columns 1..rows; prints digit when i == j.
k (right)intScans columns rows-1..1; prints digit when i == k.
Cell outputstringDigit when condition matches; otherwise a space.
Row widthintAbout 2n-1 characters per row.

Minimal workflow

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

Approach comparison

ApproachIdeaBest for
Two inner loopsLeft i == j, right i == k with spaces elsewhereLearning and interviews
Ternary operatori == j ? j.ToString() : " "Compact one-liners
User-input rowsint.TryParse(...)Flexible row count
Compact tracerows = 3 on paper firstQuick dry-runs before full demo
Full X patterni == j || i + j == rows + 1 in one loopExtension after mastering V-shape

⚡ Quick Reference

GoalPattern
Outer loopfor (i = 1; i <= rows; i++)
Left halffor (j = 1; j <= rows; j++) Console.Write(i == j ? j.ToString() : " ");
Right halffor (k = rows - 1; k >= 1; k--) Console.Write(i == k ? k.ToString() : " ");
End rowConsole.WriteLine();
Skip center duplicateRight loop starts at rows - 1, not rows
Program 52 contrastProgram 52 uses palindromic m++/m--; Program 53 uses diagonal conditions

📋 Fixed Rows vs User Input vs Compact Trace

Same V-shape — three ways to set row count and trace the logic.

Fixed rows
rows = 5

Hard-coded height for demos

User input
TryParse

Read row count from console

Compact trace
rows = 3

Quick dry-run on paper

Left diagonal
i == j

Main diagonal digit placement

Right diagonal
i == k

Mirrored diagonal digit placement

Context

When This Pattern Shows Up

Reach for this pattern when teaching conditional diagonal placement, mirrored halves, and spacing in console output.

  1. Post Program 52 exercise

    Natural follow-up after Program 52’s palindromic pyramid — introduces i == j diagonal conditions.

  2. Diagonal drills

    Each row places digits only where indices match — good bridge to matrix and grid problems.

  3. Two halves per row

    Each row scans about 2n-1 positions — classic nested-loop O(n²) complexity.

  4. Gateway to Program 54

    Program 54 mirrors this V-shape downward to form a full diamond — compare the two 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 diagonal conditions, mirrored halves, and O(n²) thinking.

🔮 Live Preview

Choose row count between 3 and 9 and draw the mirror diagonal number pattern in the browser.

Try 4, 5, or 7. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete C# programs — fixed rows, user input, and a compact trace demo. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the mirror diagonal V-shape with conditional digit placement on both diagonals.

Example 1 — Fixed rows = 5

Hard-coded row count — print digit when i == j or i == k, otherwise print a space.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int rows = 5;

            for (int i = 1; i <= rows; i++)
            {
                for (int j = 1; j <= rows; j++)
                    Console.Write(i == j ? j.ToString() : " ");

                for (int k = rows - 1; k >= 1; k--)
                    Console.Write(i == k ? k.ToString() : " ");

                Console.WriteLine();
            }
        }
    }
}

How It Works

When i = 3, the left loop prints spaces until j = 3, then the right loop prints spaces until k = 3 — output 3 3. When i = 5, only the center column gets a digit because both diagonals meet at the bottom tip.

📈 User Input

Read row count from the console with safe parsing.

Example 2 — User Input Rows

Read rows from the console with int.TryParse — reject invalid input gracefully.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the number of rows: ");
            if (!int.TryParse(Console.ReadLine(), out int rows) || rows <= 0)
            {
                Console.WriteLine("Please enter a positive integer.");
                return;
            }

            for (int i = 1; i <= rows; i++)
            {
                for (int j = 1; j <= rows; j++)
                    Console.Write(i == j ? j.ToString() : " ");

                for (int k = rows - 1; k >= 1; k--)
                    Console.Write(i == k ? k.ToString() : " ");

                Console.WriteLine();
            }
        }
    }
}

How It Works

Same diagonal two-loop core as Example 1; only the source of rows changes from a literal to user input.

⚡ Compact Trace

Smaller row count for quick tracing on paper or in interviews.

Example 3 — Compact rows = 3

Use rows = 3 to trace left and right diagonal conditions before scaling to 5 rows.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int rows = 3;

            for (int i = 1; i <= rows; i++)
            {
                for (int j = 1; j <= rows; j++)
                    Console.Write(i == j ? j.ToString() : " ");

                for (int k = rows - 1; k >= 1; k--)
                    Console.Write(i == k ? k.ToString() : " ");

                Console.WriteLine();
            }
        }
    }
}

How It Works

With only three rows you can trace every i == j and i == k check on paper before running the full rows = 5 demo.

🧠 How the Algorithm Prints Rows

1

Set rows

int rows = 5; controls how many V-shaped lines print.

Setup
2

Scan left half

for (j = 1; j <= rows; j++) — print digit when i == j, else space.

Left
3

Scan right half

for (k = rows - 1; k >= 1; k--) — print digit when i == k, else space.

Right
4

End the row

Console.WriteLine() after both inner loops finish the current line.

Newline
=

Mirror diagonal V complete

Each row prints about 2n-1 characters — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each row’s left diagonal position, right diagonal position, and full line output.

iLeft (j)Right (k)Row output
1j = 1k = 11 1
2j = 2k = 22 2
3j = 3k = 33 3
4j = 4k = 44 4
5j = 5(none — center tip)5

Row 5 prints only one digit because the right loop starts at rows - 1, avoiding a duplicate center column.

Use Cases

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

1. Teaching Nested Loops

Each row scans a fixed-width grid with conditional digit placement.

Example: trace row i = 3 in the walkthrough table.

2. Diagonal Drills

Each row mirrors digits on two diagonals — good bridge to matrix indexing.

Example: row 5 ends with a single center digit 5 at the V tip.

3. Console Formatting Drills

Practice Write vs WriteLine with multiple values per row.

Example: put WriteLine inside the inner loop by mistake.

4. Grid Scanning

Each row prints about 2n-1 characters — links loops to grid traversal.

Example: 10 rows scan about 19 characters on the widest line.

5. Complexity Intuition

Growing inner bound makes O(n²) concrete — count prints for n rows.

Example: 5 rows scan about 9 characters per line on average.

6. Input Validation Labs

Pair the pattern with TryParse and positive-row checks.

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

Pro Tip: when an interviewer asks for patterns, explain 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 C# courses.

  1. 1. Instant Visual Feedback

    Wrong conditions show up immediately as misaligned diagonals.

  2. 2. Real Math Connection

    Each row uses real diagonal logic — not abstract loop drill.

  3. 3. Easy to Extend

    Change rows, use fixed-width format, or switch to full rectangular table.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace row i = 3 on paper — watch both loops print 3 at column 3 with spaces elsewhere.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Left loop j = 1..rows

    Scan all columns in the left half — print digit only when i == j.

  2. 2. Prefer TryParse

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

  3. 3. WriteLine After Inner Loop

    Only call WriteLine() after the inner loop finishes the row.

  4. 4. Right loop k = rows-1..1

    Start the right loop at rows - 1 to skip duplicating the center column.

  5. 5. Dry-Run rows = 5

    Trace five rows on paper before coding the full 10-row demo.

Pro Tip: if the output is a vertical list of single numbers, you almost certainly put WriteLine inside the inner loop.

Common Pitfalls

Mistakes that commonly break mirror diagonal number patterns.

  1. 1. WriteLine Inside Inner Loop

    Each character lands on its own line — you get a column, not a V-shape.

    → Use Console.Write(...) for digits and spaces; WriteLine only after both inner loops.

  2. 2. Wrong Right Loop Start

    Starting the right loop at k = rows duplicates the center digit on the bottom row.

    → Use for (k = rows - 1; k >= 1; k--) — skip the center column.

  3. 3. Using i != j Instead of i == j

    Digits appear everywhere instead of on the diagonals only.

    → Print the digit when i == j (or i == k), not when they differ.

  4. 4. Forgetting WriteLine After Row

    All numbers print on one long line without row breaks.

    → Add Console.WriteLine() after both inner loops complete.

  5. 5. Blind Convert.ToInt32

    Letters or empty input throw FormatException.

    → Prefer int.TryParse and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

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

rows = 0

Empty output

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

Negative

rows < 0

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

rows = 5

Compact trace

Five rows ending with a single center 5 — good for dry-runs.

Bad input

Non-numeric ReadLine

Convert.ToInt32 throws — use TryParse.

Large rows

Wide output

Row 9 scans 17 character positions — total work grows as O(n²).

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 52

  • Program 52 uses palindromic m++/m-- rows
  • Program 53 uses spacing and i == j diagonal conditions

2. Change rows

  • Try rows = 4 or rows = 7 in the live preview
  • Same diagonal logic, different V height

3. Next in series

  • Continue with Program 54
  • Mirror this V-shape downward to form a diamond

4. Print a full X

  • Use i == j || i + j == rows + 1 in one column loop
  • Same conditions, both diagonals in a single scan

Notes

  • Two inner loops. Left: j = 1..rows with i == j. Right: k = rows-1..1 with i == k. Else print a space.
  • Console.Write stays on the line; WriteLine advances — call it only after both inner loops finish.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single 1.
  • Each row prints about 2n-1 characters — total work is O(n²) for n rows.

Quick Takeaway: outer i = 1..rows, left i == j, right i == k, else space, then WriteLine().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Characters per rowAbout 2n-1No storage beyond loop counters
Wrap Up

🎉 Conclusion

The mirror diagonal number pattern is a natural follow-up to Program 52: conditional digit placement on mirrored diagonals with spaces elsewhere. Master the fixed-rows version, then try user input and the compact 3-row trace.

Practice the three examples above, then continue to Program 54 to mirror this V-shape into a full diamond.

Row i prints digit i on both diagonals — left with i == j, right with i == k.

💡 Best Practices

✅ Do

  • Left loop: for (j = 1; j <= rows; j++) Console.Write(i == j ? j.ToString() : " ");
  • Right loop: for (k = rows - 1; k >= 1; k--) Console.Write(i == k ? k.ToString() : " ");
  • Start the right loop at rows - 1 to skip center duplication
  • Call WriteLine() after both inner loops
  • Use int.TryParse for user input

❌ Don’t

  • Start right loop at k = rows — duplicates the center digit
  • Print digits when i != j — fills the whole row with numbers
  • Call WriteLine inside either inner loop
  • Ignore bad console input in user-facing demos
  • Skip the rows = 3 dry-run before coding rows = 5

Key Takeaways

Knowledge Unlocked

Five things to remember about this mirror diagonal pattern

Print the V-shape the beginner-friendly way.

5
Core concepts
02

Left

i == j

Code
03

Right

i == k

Code
04

Skip center

k = rows - 1..1

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The mirrored half prints rows-1 positions to avoid duplicating the center column. On the final row, only the main diagonal digit remains.
It prints the row number on the main diagonal (left) and on a mirrored diagonal (right), creating a symmetric V-shape like 1..5 on both sides.
The first loop prints the left half across rows columns. The second prints the right mirrored half across rows-1 columns in reverse.
Skipping the center column prevents printing the middle digit twice on rows where i equals the center index.
Change rows or read it from user input with TryParse — see Example 2.
O(n²) for n rows because each row prints about 2n-1 characters using nested loops.
Program 52 builds palindromic digit rows with m++ and m--. Program 53 uses spacing and i == j / i == k to place digits on mirrored diagonals.
Yes. Print when i == j or i + j == rows + 1 in a single column loop.
Prefer int.TryParse(Console.ReadLine(), out rows) so bad input does not throw FormatException.
One row prints a single 1 — the left loop prints at j = 1 and the right loop does not run.

Did you Know? 🔊

Each row prints the row number on the main diagonal (left) and on a mirrored diagonal (right) using i == j and i == k. Row 3 shows 3 on both sides — about 2n-1 characters per row, so O(n²) total.

Continue to Program 54

Mirror this V-shape downward to form a full diamond in the next tutorial.

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