Mirrored Number Pattern in C

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Space Alignment

What You’ll Learn

The mirrored number pattern prints 1 1, 12 21, 123 321, 1234 4321, 1234554321 — a natural step after the 0-centered mirror in Program 28. This tutorial covers fixed-width loops, space alignment, conditional printing, a live preview, worked C examples, edge cases, and complexity.

Shape Rule

Left + right mirror

Left half grows 1..i; right half mirrors i..1 with spaces keeping alignment.

Outer Loop

i = 1..rows

for (i = 1; i <= rows; i++) — one mirrored row per iteration.

Left Loop (j)

1..rows

if (j <= i) prints digit; else prints a space.

Right Loop (k)

rows..1

if (k > i) prints space; else prints k.

Live Preview

3–9 rows

Pick a row count and draw the spaced mirror pattern in the browser.

O(n²)

Complexity

Each row runs two loops of width rows — total work scales as .

Introduction

A mirrored number pattern prints an increasing left half (1..i) and a decreasing right half (i..1) on the same row. With rows = 5, spaces keep both halves aligned until the final row joins as 1234554321.

In C you use fixed-width inner loops: left loop prints digits or spaces with j <= i, right loop mirrors with k > i for spaces.

Why it matters?

It combines conditional printing with space alignment — a step up from Program 28’s digit-only mirror.

Key Highlights

Fixed width

Both inner loops always run rows times.

Left j <= i

Print digit or space on the left half.

Right k > i

Print space or digit on the right half.

Series Foundation

Follow Program 28; continue to Program 30 (right-aligned triangle) next.

In short: for each i, left loop prints j or space, right loop prints k or space, then printf("\n").

📝 Problem & Approach

Given rows = 5, print a mirrored pattern: for each i, print digits or spaces in a fixed-width left loop, then digits or spaces in a fixed-width right loop.

c
// rows = 5 (conceptual shape)
// 1        1
// 12      21
// 123    321
// 1234  4321
// 1234554321

Inputs & Outputs

ItemTypeDescription
rowsintPattern height — also the fixed width of both inner loops.
iintOuter loop — current row; controls how many digits print on each side.
jintLeft loop — prints j when j <= i, else a space.
kintRight loop — prints k when k <= i, else a space.

Minimal workflow

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

Approach comparison

ApproachIdeaBest for
if/else per loop1 1, 12 21, …Learning and interviews
Ternary operator(j <= i) ? printf("%d", j) : printf(" ");Compact console programs
User-input rowsscanf("%d", &rows);Flexible row count

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= rows; i++)
Left halfif (j <= i) printf("%d", j); else printf(" ");
Right halfif (k > i) printf(" "); else printf("%d", k);
End the rowprintf("\n");
Ternary form(j <= i) ? printf("%d", j) : printf(" ");
User inputscanf("%d", &rows);

📋 if/else vs Ternary vs User Input

Same spaced mirror — different ways to write the conditions and control rows.

Outer loop
i = 1..rows

One mirrored row per iteration

Left half
j <= i ? j : " "

Digit or space

Right half
k > i ? " " : k

Space or digit

Learning tip
2 x rows

Both loops always width rows

Context

When This Pattern Shows Up

Reach for this pattern when teaching fixed-width loops, space alignment, and conditional character output.

  1. Post 0-center exercise

    Natural follow-up after Program 28 — introduces space padding for symmetric alignment.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with scanf for a flexible row count.

  4. Gateway to variants

    Compare Program 28 (0-centered mirror) and Program 30 (right-aligned triangle) 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 3 and 9 and draw the spaced mirror 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 with ternary form, and a smaller trace demo. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the spaced mirror with if/else in both inner loops.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

c
#include <stdio.h>

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

    for (i = 1; i <= 5; ++i) {
        for (j = 1; j <= 5; ++j) {
            if (j <= i)
                printf("%d", j);
            else
                printf(" ");
        }

        for (k = 5; k >= 1; --k) {
            if (k > i)
                printf(" ");
            else
                printf("%d", k);
        }

        printf("\n");
    }

    return 0;
}

How It Works

When i = 1, the left loop prints 1 and four spaces; the right prints four spaces then 1 — output 1 1. When i = 5, both halves fill all columns — output 1234554321 with no gap.

📈 User Input

Read the row count with scanf instead of hard-coding 5.

Example 2 — User Input

Read rows with scanf("%d", &rows); both inner loops use rows as the width.

c
#include <stdio.h>

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

    printf("Enter rows: ");
    scanf("%d", &rows);
    if (rows < 1) return 0;

    for (i = 1; i <= rows; ++i) {
        for (j = 1; j <= rows; ++j)
            (j <= i) ? printf("%d", j) : printf(" ");

        for (k = rows; k >= 1; --k)
            (k > i) ? printf(" ") : printf("%d", k);

        printf("\n");
    }

    return 0;
}

How It Works

Same spaced-mirror core as Example 1; ternary operators replace if/else and rows replaces hard-coded 5. Non-numeric input leaves rows unset if you ignore scanf’s return value — always check it in safer labs.

⚡ Smaller Demo

Run with rows = 3 to trace every row on paper before scaling up.

Example 3 — Compact rows = 3

Same if/else logic with a smaller row count for quick tracing.

c
#include <stdio.h>

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

    for (i = 1; i <= rows; ++i) {
        for (j = 1; j <= rows; ++j) {
            if (j <= i) printf("%d", j);
            else printf(" ");
        }

        for (k = rows; k >= 1; --k) {
            if (k > i) printf(" ");
            else printf("%d", k);
        }

        printf("\n");
    }

    return 0;
}

How It Works

Only rows changes from 5 to 3 — the if/else structure stays identical. Trace i = 1, 2, 3 on paper to see how spaces shrink each row.

🧠 How the Algorithm Prints Rows

1

Set up

#include <stdio.h> brings in printf / scanf. Set loop variables i, j, k with rows = 5.

Setup
2

Outer loop walks rows

for (i = 1; i <= rows; i++) — ascending outer loop; one mirrored row per iteration.

Row
3

Left loop (j)

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

Left
4

Right loop (k)

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

Right
5

New line

printf("\n") ends the row after both inner loops finish.

Break
=

Spaced mirror complete

Spaces shrink each row until the final join — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of i, what the left and right loops print, and the full row output.

iLeft (j)Right (k)Row output
11, space, space, space, spacespace, space, space, space, 11 1
21, 2, space, space, spacespace, space, space, 2, 112 21
31, 2, 3, space, spacespace, space, 3, 2, 1123 321
41, 2, 3, 4, spacespace, 4, 3, 2, 11234 4321
51, 2, 3, 4, 55, 4, 3, 2, 11234554321

Gap spaces = 2 * (rows - i) between the left and right digit groups — zero when i = rows.

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: flip j <= i to j > i for digits and watch alignment break.

2. Pattern Series Base

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

Example: continue to Program 30 for a right-aligned descending triangle.

3. Console Formatting Drills

Practice Write vs printf("\n") without complex math.

Example: put printf("\n") inside the inner loop by mistake.

4. Padding character

Add spaces between digits once the two-loop structure works.

Example: use printf("%d ", j) in both inner loops.

5. Complexity Intuition

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

Example: count printed characters for rows = 5 — each row prints 2 * rows characters.

6. Input Validation Labs

Pair the pattern with scanf return checks and positive-row checks.

Example: reject max <= 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 C 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: trace i, j, and k on paper for rows = 3 before coding — watch how gap spaces shrink each row.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Match Loop Widths

    Both inner loops must use rows as the bound — mismatched widths break alignment.

  2. 2. Prefer scanf

    Check the return value so bad input does not leave rows uninitialized.

  3. 3. Keep printf("\n") Outside

    Only call printf("\n") after the inner loop finishes the row.

  4. 4. Trace i, j, and k on Paper

    Mark the ascending half and mirror half for each row before coding.

  5. 5. Dry-Run rows = 3

    Trace i = 1..3 on paper before coding the full rows = 5 demo.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put printf("\n") inside the inner loop.

Common Pitfalls

Mistakes that commonly break spaced mirror patterns.

  1. 1. Newline Inside the Inner Loop

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

    → Use printf("%d", j), printf(" "), or printf("%d", k); printf("\n") only after both inner loops.

  2. 2. Flipping Left vs Right Conditions

    Using k <= i for spaces on the right (instead of k > i) inverts the mirror half.

    → Left: print digit when j <= i. Right: print space when k > i.

  3. 3. Skipping Spaces

    Printing only digits without padding collapses the symmetric shape into a tight palindrome.

    → Use printf(" ") in the else branches to maintain fixed width.

  4. 4. Different Loop Bounds

    Left loop to i but right loop to rows - 1 misaligns columns.

    → Both inner loops must run exactly rows iterations.

  5. 5. Unchecked scanf

    Letters or empty input leave rows uninitialized.

    → Check scanf return value and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is 11 — both halves print one digit with no gap.

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.

rows = 2

Smallest mirror

Two rows: 1 1 and 1221.

Bad input

Non-numeric scanf input

Unchecked scanf leaves rows unset — check the return value.

Large rows

Large row count

Each row prints 2 * rows characters — grows as rows² total work.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. 0-centered mirror

  • Three loops with fixed zero center
  • Review Program 28

2. Right-aligned triangle

  • Spaces on the left, digits on the right
  • Continue with Program 30

3. Tight palindrome

  • Remove spaces — compare with Program 27
  • See how alignment changes the shape

4. Custom gap character

  • Replace " " with "." or "*"
  • Same if/else structure, different padding

Notes

  • Alignment rule. Left loop: digit when j <= i, space otherwise. Right loop: space when k > i, digit otherwise.
  • printf stays on the line; printf("\n") advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 prints 11.
  • Both inner loops must run exactly rows times — fixed width is what creates the alignment.

Quick Takeaway: outer loop i = 1..rows, left j <= i ? j : " ", right k > i ? " " : k, then printf("\n").

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The mirrored number pattern is a compact lesson in fixed-width loops and space alignment: print digits or spaces on the left with j <= i, mirror on the right with k > i, and end each row with printf("\n"). Master the fixed-rows version, then try user input and a smaller trace demo.

Practice the three examples above, then continue to Program 30 for the right-aligned descending number triangle.

Both inner loops must use rows as the width — validate rows when reading from the console.

💡 Best Practices

✅ Do

  • Use for (i = 1; i <= rows; i++) in the outer loop
  • Left: if (j <= i) print digit, else print space
  • Right: if (k > i) print space, else print k
  • Keep both inner loops at width rows
  • Check scanf return value before using rows

❌ Don’t

  • Call printf("\n") inside either inner loop
  • Use different bounds for left and right loops
  • Flip the space/digit conditions between halves
  • Skip spaces in the else branches
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this spaced mirror

Print the pattern the beginner-friendly way.

5
Core concepts
02

Fixed width

2 x rows

Code
+ 03

Left j<=i

Digit or space

Code
04

Right k>i

Space or digit

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Spaces keep the left and right halves aligned so the pattern looks symmetric. Without them, the right half shifts left each row.
The right loop runs k from rows down to 1. When k > i it prints a space; otherwise it prints k — building i..1 on the right.
Both inner loops always run rows times. Extra positions are filled with spaces so columns stay aligned.
Program 27 prints a tight palindrome with no alignment spaces. Program 29 uses fixed-width loops and spaces for a symmetric diamond shape.
When i equals rows, both halves fill all columns — 12345 on the left and 54321 on the right meet with no space between.
Replace 5 with rows in both inner loop bounds — see Example 2.
O(n²) for n rows because each row runs two inner loops of width n.
Check scanf's return value: if (scanf("%d", &rows) != 1) handle bad input. Unchecked scanf leaves rows uninitialized on failure.
Yes — (j <= i) ? printf("%d", j) : printf(" ") compacts the if/else logic.

Did you Know? 🔊

This pattern prints an increasing left half (1..i), then a mirrored right half (i..1). Spaces in the fixed-width loops keep both halves aligned until the final row joins without a gap.

Continue to Program 30

Move on to the right-aligned descending number triangle in the C number-pattern series.

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