Diagonal Mirror Number Pyramid Pattern in C++

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

What You’ll Learn

Program 57 prints a diagonal mirror number pyramid: each row shows the row number twice — once on the left diagonal and once on the right — with spaces everywhere else. A natural step after Program 56’s centered palindromic pyramid. This tutorial covers conditional printing, two inner loops per row, a live preview, worked C examples, edge cases, and complexity.

Shape Rule

Mirror diagonals

Row i prints the digit i on the left diagonal and again on the right diagonal — an inverse-V mirror shape.

Outer Loop

i = 1..rows

for (i = 1; i <= rows; i++) picks the current row and the digit to place on both diagonals.

Left Diagonal

j = rows..1

(i == j ? cout << j : cout << " ") — scans from the right edge inward.

Right Diagonal

k = 2..rows

(i == k ? cout << k : cout << " ") — mirrors the left half from column 2 onward.

Conditional Print

digit or space

Every column position gets either the row digit or a single space — no other characters.

O(n²)

Complexity

Each row scans about 2×rows-1 positions — total work grows as O(n²).

Introduction

A diagonal mirror number pyramid prints the row number on two mirror diagonals with spaces everywhere else. With rows = 5, you get 1, 2 2, 3 3, and so on — forming an inverse-V shape.

In C use an outer loop for rows, then two inner loops: the first scans j = rows..1 for the left diagonal, the second scans k = 2..rows for the right diagonal, printing the digit only when i == j or i == k.

Why it matters?

It bridges Program 56’s palindromic rows to conditional diagonal placement — combining if checks with two inner loops per row.

Key Highlights

Left diagonal

j = rows..1, print when i == j.

Right diagonal

k = 2..rows, print when i == k.

vs Program 56

Program 56 prints palindromic rows; Program 57 prints the row digit twice on mirror diagonals.

Series Foundation

Follow Program 56; continue to Program 58 next.

In short: outer i = 1..rows, left loop j = rows..1, right loop k = 2..rows, print digit or space, then cout << "\n".

📝 Problem & Approach

Given row count rows = 5, print a diagonal mirror number pyramid — row i shows digit i on left and right diagonals with spaces elsewhere.

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

Inputs & Outputs

ItemTypeDescription
rowsintPyramid height — bottom row has rows on both diagonals.
i (outer)intCurrent row index — runs 1 to rows.
j (left)intScans rows..1 — prints digit when i == j.
k (right)intScans 2..rows — prints digit when i == k.
Positions per rowintrows + (rows - 1) = 2×rows - 1 character slots.
Digits per rowintExactly 2 (except row 1 when right loop is empty for rows = 1).

Minimal workflow

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

Approach comparison

ApproachIdeaBest for
Two inner loopsLeft j = rows..1, right k = 2..rowsLearning and interviews
Conditional printif (i == j) digit else spaceDiagonal placement drills
User-input rowscin >> rowsFlexible pyramid size
Compact tracerows = 3 on paper firstQuick dry-runs before full demo
Character swapReplace digit with * for an X-shapeVisual debugging

⚡ Quick Reference

GoalPattern
Outer loopfor (i = 1; i <= rows; i++)
Left diagonalfor (j = rows; j >= 1; j--) (i == j ? cout << j : cout << " ");
Right diagonalfor (k = 2; k <= rows; k++) (i == k ? cout << k : cout << " ");
End rowcout << "\n";
Program 56 contrastProgram 56 uses palindromic rows; Program 57 uses mirror diagonals

📋 Fixed Rows vs User Input vs Compact Trace

Same diagonal mirror pyramid — three ways to set row count and trace the logic.

Fixed rows
rows = 5

Hard-coded height for demos

User input
cin >> rows

Read row count from console

Compact trace
rows = 3

Quick dry-run on paper

Left half
j = rows..1

Print when i == j

Right half
k = 2..rows

Print when i == k

Context

When This Pattern Shows Up

Reach for this pattern when teaching conditional printing, diagonal placement, and combining two inner loops per row.

  1. Post Program 56 exercise

    Natural follow-up after Program 56’s palindromic pyramid — introduces conditional diagonal placement.

  2. Diagonal drills

    Each row places digits on mirror diagonals — good bridge to matrix diagonal problems.

  3. Two loops per row

    Left and right halves with if checks — concrete nested-loop practice.

  4. Gateway to Program 58

    Program 58 extends this diagonal logic to a full diamond — compare after mastering this pyramid.

  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 conditional printing, mirror diagonals, and O(n²) thinking.

🔮 Live Preview

Choose row count between 3 and 9 and draw the centered diagonal mirror number pyramid 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 a diagonal mirror pyramid with five rows — left and right inner loops with conditional printing per row.

Example 1 — Fixed rows = 5

Hard-coded row count — scan left diagonal j = rows..1, then right diagonal k = 2..rows, printing digit or space.

C++
#include <iostream>
using namespace std;

int main() {
    int rows = 5;
    int i, j, k;

    for (i = 1; i <= rows; i++) {
        for (j = rows; j >= 1; j--)
            (i == j ? cout << j : cout << " ");

        for (k = 2; k <= rows; k++)
            (i == k ? cout << k : cout << " ");

        cout << "\n";
    }

    return 0;
}

How It Works

When i = 3, the left loop prints spaces then 3 at j = 3; the right loop prints spaces then 3 at k = 3 — output 3 3. When i = 1, only the left loop places a digit; the right loop is all spaces.

📈 User Input

Read row count from the console with safe parsing.

Example 2 — User Input Rows

Read rows with cin >> rows (check cin.fail()) — reject invalid input gracefully.

C++
#include <iostream>
using namespace std;

int main() {
    int rows;
    int i, j, k;

    cout << "Enter the number of rows: ";
    cin >> rows;
    if (cin.fail() || rows <= 0) {
        cout << "Please enter a positive integer.\n";
        return 1;
    }

    for (i = 1; i <= rows; i++) {
        for (j = rows; j >= 1; j--)
            (i == j ? cout << j : cout << " ");

        for (k = 2; k <= rows; k++)
            (i == k ? cout << k : cout << " ");

        cout << "\n";
    }

    return 0;
}

How It Works

Same conditional diagonal logic 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 loops before scaling to 5 rows.

C++
#include <iostream>
using namespace std;

int main() {
    int rows = 3;
    int i, j, k;

    for (i = 1; i <= rows; i++) {
        for (j = rows; j >= 1; j--)
            (i == j ? cout << j : cout << " ");

        for (k = 2; k <= rows; k++)
            (i == k ? cout << k : cout << " ");

        cout << "\n";
    }

    return 0;
}

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 pyramid height and the maximum digit printed.

Setup
2

Scan left diagonal

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

Left half
3

Scan right diagonal

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

Right half
4

End the row

Call cout << "\n" after both inner loops finish — one mirror-diagonal row complete.

Newline
=

Diagonal mirror pyramid complete

Each row scans 2×rows-1 positions — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

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

iLeft hit (j)Right hit (k)Row output
1j = 1(none)1
2j = 2k = 22 2
3j = 3k = 33 3
4j = 4k = 44 4
5j = 5k = 55 5

Row i always prints exactly two digits (one per diagonal) when rows > 1 — spaced across 2×rows-1 character positions.

Use Cases

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

1. Teaching Nested Loops

Two inner loops with conditional printing — classic diagonal placement drill.

Example: trace each row in the walkthrough table — left hit, right hit.

2. Diagonal Drills

Each row mirrors digits on two diagonals — compare with Program 53’s single diagonal V-shape.

Example: row 5 prints 5 at column 5 and again at column 9.

3. Output Formatting Drills

Practice cout vs cout << "\n" with digit-or-space decisions per column.

Example: put cout << "\n" inside the inner loop by mistake.

4. Why k starts at 2

Starting the right loop at 2 avoids a third digit at the center — keeps exactly two prints per row.

Example: try k = 1 and see the center digit triple on some rows.

5. Complexity Intuition

Each row scans about 2n positions — makes O(n²) concrete for beginners.

Example: row 5 with rows = 5 scans 9 character slots — see the walkthrough table.

6. Input Validation Labs

Pair the pattern with cin >> rows return checks and positive-row validation.

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

    Each row instantly forms an inverse-V — two digits on mirror diagonals make the shape obvious.

  2. 2. Real Math Connection

    Conditional digit-or-space printing teaches real console alignment — not abstract loop drill.

  3. 3. Easy to Extend

    Swap digits for * to get an X-shape, or extend to Program 58’s full diamond.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace rows = 3 on paper — row 2 shows 2 2 with one space between the digits.

Usage Tips

Small habits that keep number-pattern code clean.

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

    Print the digit when i == j; otherwise print a single space.

  2. 2. Check cin.fail()

    Avoid using uninitialized rows when the user types letters instead of a number.

  3. 3. Newline After Both Inner Loops

    Only call cout << "\n" after both inner loops finish the row.

  4. 4. Right loop starts at k = 2

    Use for (k = 2; k <= rows; k++) so the center position is not duplicated.

  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 cout << "\n" inside the inner loop.

Common Pitfalls

Mistakes that commonly break diagonal mirror number pyramid patterns.

  1. 1. cout << "\n" Inside Inner Loop

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

    → Use (i == j ? cout << j : cout << " ") or cout << " "; call cout << "\n" only after both inner loops.

  2. 2. Right Loop Starts at 1

    Starting at k = 1 can print a third digit at the center — row looks crowded.

    → Use for (k = 2; k <= rows; k++) — mirror from column 2 onward.

  3. 3. Wrong Condition Check

    Using j == rows instead of i == j places digits on the wrong diagonal.

    → Always compare the outer row index i with the inner loop variable j or k.

  4. 4. Forgetting Newline After Row

    All numbers print on one long line without row breaks.

    → Add cout << "\n" after both inner loops complete.

  5. 5. Unchecked cin

    Letters or empty input leave rows uninitialized or wrong.

    → Check cin.fail() after cin >> rows 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 (k = 2..1) 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

Bottom row has two copies of 5 across 9 positions — good for dry-runs before scaling up.

Bad input

Non-numeric input

Unchecked cin >> rows fails silently — check the return value.

Large rows

Wide output

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

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 56

  • Program 56 prints centered palindromic rows (1..i..1)
  • Program 57 prints the row digit twice on mirror diagonals

2. Build Program 58 diamond

  • Print this pyramid, then add the inverted bottom half
  • Compare with Program 58’s full diagonal mirror diamond

3. Next in series

  • Continue with Program 58
  • Extend diagonal logic to a full diamond shape

4. Character swap

  • Replace the digit branch with cout << "*" for a star pattern
  • Same loops, clean X-shape for visual debugging

Notes

  • Two inner loops. Left: j = rows..1, print when i == j. Right: k = 2..rows, print when i == k.
  • cout stays on the line; cout << "\n" advances — call it only after both inner loops finish.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single 1 on the left diagonal.
  • Row i scans 2×rows-1 positions — total work grows as O(n²) for n rows.

Quick Takeaway: left j = rows..1, right k = 2..rows, digit or space, then cout << "\n".

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Digits on row i2i - 1No storage beyond loop counters
Wrap Up

🎉 Conclusion

The diagonal mirror number pyramid is a natural follow-up to Program 56: each row places the row digit on two mirror diagonals with conditional printing. Master the fixed-rows version, then try user input and the compact 3-row trace.

Practice the three examples above, then continue to Program 58 for the full diagonal mirror diamond.

Row i prints two copies of digit i — one on each mirror diagonal across 2×rows-1 positions.

💡 Best Practices

✅ Do

  • Left: for (j = rows; j >= 1; j--) with if (i == j)
  • Right: for (k = 2; k <= rows; k++) with if (i == k)
  • Print a single space for non-matching positions
  • Call cout << "\n" after both inner loops
  • Use cin >> rows with return-value checks for user input

❌ Don’t

  • Start right loop at k = 1 — can triple-print at center
  • Use j == rows instead of i == j — wrong diagonal
  • Call cout << "\n" inside any 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 diagonal mirror pyramid

Print the mirror-diagonal pyramid the beginner-friendly way.

5
Core concepts
02

Left

j = rows..1

Code
03

Right

k = 2..rows

Code
04

Check

i == j or i == k

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The left inner loop places the row number on the left diagonal; the right inner loop mirrors it on the right diagonal.
Starting at k = 2 avoids duplicating the center position — each row prints the number at most twice.
Row i shows the digit i on two diagonals with spaces between, e.g. row 3 with rows = 5: ' 3 3'.
Program 56 prints a centered palindromic row (1..i..1). Program 57 prints only the row number twice on mirror diagonals.
Each column position gets either the row digit or a space — the conditions pick exactly two print positions per row.
Change rows or read it from user input with cin — see Example 2.
O(n²) for n rows because each row scans about 2n character positions.
NaN
After cin >> rows, check cin.fail() or use a while (!(cin >> rows)) loop to re-prompt on bad input.
One row prints a single 1 — the right loop (k = 2..1) does not run.

Did you Know? 🔊

Each row prints the row number twice — once on the left diagonal and once on the right — with spaces everywhere else. Total positions per row = 2×rows-1.

Continue to Program 58

Move on to the full diagonal mirror diamond in the C++ number-pattern series.

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