Number Diamond Pattern in C#

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

What You’ll Learn

The centered number diamond prints 1, 123, 12345, … 123456789, then mirrors back down — a natural follow-up after Program 43’s right-aligned triangle. This tutorial covers two outer loops, centering spaces, ascending digit sequences, a live preview, worked C# examples, edge cases, and complexity.

Shape Rule

Diamond halves

Top half grows 1..levels; bottom half mirrors levels-1..1.

Top Loop

i = 1..levels

for (i = 1; i <= levels; i++) — builds the growing half of the diamond.

Bottom Loop

i = levels-1..1

for (i = levels - 1; i >= 1; i--) — mirrors the top half back down.

Space Loop

Center rows

Leading spaces before digits — j = i..levels-1 on top, j = levels..i+1 on bottom.

Live Preview

Levels 3–5

Pick a height and draw the centered number diamond in the browser.

O(n²)

Complexity

Each row prints 2*i-1 digits — total work scales as .

Introduction

A centered number diamond prints ascending digit sequences on each row, growing to a peak then mirroring back down. With levels = 5, you get 1, 123, … 123456789, then the same rows in reverse.

In C# you use two outer loops (top and bottom halves), a space loop to center each row, and an inner loop that prints digits 1 to 2*i-1.

Why it matters?

It combines symmetric diamond logic with centering spaces — a step up from Program 43’s right-aligned triangle.

Key Highlights

2*i-1 digits

Inner loop k < i*2.

Centering

Leading spaces per row.

Two halves

Top 1..levels, bottom levels-1..1.

Series Foundation

Follow Program 43; continue to Program 45 next.

In short: top loop i = 1..levels, space loop then digits k = 1..2*i-1, bottom loop i = levels-1..1, then WriteLine().

📝 Problem & Approach

Given levels = 5, print a centered number diamond: top half i = 1..levels, bottom half i = levels-1..1, each row with leading spaces then digits 1 to 2*i-1.

C#
// levels = 5
//    1
//   123
//  12345
// 1234567
//123456789
// 1234567
//  12345
//   123
//    1

Inputs & Outputs

ItemTypeDescription
levelsintDiamond peak height — total lines = 2*levels - 1.
iintOuter loop — current row level (top or bottom half).
jintSpace loop — prints leading spaces to center the row.
kintNumber loop — prints digits 1..2*i-1 via k < i*2.

Minimal workflow

Pseudocode
for i from 1 to levels:
    print (levels - i) spaces
    for k from 1 to 2*i-1: print k
    print newline
for i from levels-1 down to 1:
    print (levels - i) spaces
    for k from 1 to 2*i-1: print k
    print newline

Approach comparison

ApproachIdeaBest for
Fixed levels1, 123, 12345, …Learning and interviews
User-input levelsint.TryParse(...)Flexible diamond height
Compact tracelevels = 3 on paper firstDebugging loop bounds

⚡ Quick Reference

GoalPattern
Top halffor (i = 1; i <= levels; i++)
Bottom halffor (i = levels - 1; i >= 1; i--)
Top space loopfor (j = i; j < levels; j++) Console.Write(" ");
Bottom space loopfor (j = levels; j > i; j--) Console.Write(" ");
Number loopfor (k = 1; k < i * 2; k++) Console.Write(k);
Program 43 contrastRight-aligned triangle — not a centered diamond

📋 Fixed vs User Input vs Compact Demo

Same centered number diamond — different ways to control height and trace the loops.

Top half
i = 1..levels

Growing rows to the peak

Bottom half
i = levels-1..1

Mirror back down

Spaces
levels - i

Center each row

Digits
k = 1..2*i-1

Odd-length sequences

Context

When This Pattern Shows Up

Reach for this pattern when teaching symmetric diamonds, centering spaces, and two-phase loop structures.

  1. Post triangle exercise

    Natural follow-up after Program 43 — introduces centering spaces and a mirrored bottom half.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with ReadLine for a flexible row count.

  4. Gateway to variants

    Compare Program 43 (right-aligned triangle) and Program 45 (next in series) 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 height between 3 and 5 and draw the centered number diamond in the browser.

Try 3, 4, or 5. Levels between 3 and 5 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

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

📚 Getting Started

Print a centered diamond with levels = 5 using space loops and ascending digit sequences.

Example 1 — Fixed levels = 5

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

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j, k;

            for (i = 1; i <= 5; i++)
            {
                for (j = i; j < 5; j++)
                    Console.Write(" ");

                for (k = 1; k < i * 2; k++)
                    Console.Write(k);

                Console.WriteLine();
            }

            for (i = 4; i >= 1; i--)
            {
                for (j = 5; j > i; j--)
                    Console.Write(" ");

                for (k = 1; k < i * 2; k++)
                    Console.Write(k);

                Console.WriteLine();
            }
        }
    }
}

How It Works

When i = 1, four spaces center a single 1. When i = 3, two spaces precede 12345. The bottom half mirrors from i = 4 down to 1.

📈 User Input

Read the level count from the console instead of hard-coding 5.

Example 2 — User Input Levels

Read levels from the console to control diamond height.

C#
using System;

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

            for (int i = 1; i <= levels; i++)
            {
                for (int j = i; j < levels; j++)
                    Console.Write(" ");

                for (int k = 1; k < i * 2; k++)
                    Console.Write(k);

                Console.WriteLine();
            }

            for (int i = levels - 1; i >= 1; i--)
            {
                for (int j = levels; j > i; j--)
                    Console.Write(" ");

                for (int k = 1; k < i * 2; k++)
                    Console.Write(k);

                Console.WriteLine();
            }
        }
    }
}

How It Works

Same space-and-number loop core as Example 1; only levels comes from user input instead of being hard-coded as 5.

⚡ Smaller Demo

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

Example 3 — Compact levels = 3

Same space and number loops with a smaller level count for quick tracing.

C#
using System;

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

            for (int i = 1; i <= levels; i++)
            {
                for (int j = i; j < levels; j++)
                    Console.Write(" ");

                for (int k = 1; k < i * 2; k++)
                    Console.Write(k);

                Console.WriteLine();
            }

            for (int i = levels - 1; i >= 1; i--)
            {
                for (int j = levels; j > i; j--)
                    Console.Write(" ");

                for (int k = 1; k < i * 2; k++)
                    Console.Write(k);

                Console.WriteLine();
            }
        }
    }
}

How It Works

Only levels changes from 5 to 3 — the space and number loops stay identical. Trace i = 1, 2, 3 on paper to see how row length grows as 2*i-1.

🧠 How the Algorithm Prints Rows

1

Set up

using System; brings in Console. Set loop variables i, j, k with levels = 5.

Setup
2

Top half

for (i = 1; i <= levels; i++) — growing rows from 1 to the peak.

Top
3

Space loop

for (j = i; j < levels; j++) on top — prints leading spaces to center the row.

Center
4

Number loop

for (k = 1; k < i * 2; k++) — prints digits 1 to 2*i-1.

Digits
5

Bottom half

for (i = levels - 1; i >= 1; i--) — mirrors the top half with a different space loop.

Mirror
=

Number diamond complete

2*levels-1 total rows — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — top half levels = 5, row i = 3

Trace row 3 on the top half — spaces, digits printed, and full row output.

StepDetailOutput so far
Space loopj = 3, 4 — two spaces
k = 1..5Prints 1234512345
WriteLineEnd row 312345

Characters per row = 2*i-1. Space count on top half = levels - i. Bottom half repeats rows 4, 3, 2, 1 in reverse.

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: skip the space loop and watch the diamond snap left.

2. Pattern Series Base

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

Example: continue to Program 45 for the next pattern in the series.

3. Console Formatting Drills

Practice Write vs WriteLine without complex math.

Example: put WriteLine inside the inner loop by mistake.

4. Padding character

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

Example: use Console.Write(k + " ") between digits for wider spacing.

5. Complexity Intuition

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

Example: count printed digits for levels = 5 — top half alone prints 25 digits.

6. Input Validation Labs

Pair the pattern with TryParse 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, space count, and digit loop on paper for levels = 3 before coding — watch how row length grows as 2*i-1.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Two Outer Loops

    Top half 1..n and bottom half n-1..1 — do not repeat the peak row.

  2. 2. Prefer TryParse

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

  3. 3. Keep WriteLine Outside

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

  4. 4. Trace Space Count on Paper

    Mark levels - i spaces before each row’s digits before coding.

  5. 5. Dry-Run levels = 3

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

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

Common Pitfalls

Mistakes that commonly break centered number diamond patterns.

  1. 1. WriteLine Inside the Inner Loop

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

    → Use Write(k); WriteLine only after the number loop.

  2. 2. Skipping the Space Loop

    Without leading spaces, the diamond loses its centered shape.

    → Run the space loop before the number loop on every row.

  3. 3. Wrong Inner Bound

    k <= i * 2 adds an extra digit — row length becomes even instead of odd.

    → Keep for (k = 1; k < i * 2; k++) for exactly 2*i-1 digits.

  4. 4. Repeating the Peak Row

    Starting the bottom loop at i = levels prints the widest row twice.

    → Bottom half starts at i = levels - 1, not levels.

  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.

levels = 1

Single row diamond

Output is just 1 — one row, no bottom half needed.

levels = 0

Empty pattern

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

Negative

levels < 1

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

levels = 2

Smallest diamond

Three rows: 1, 123, 1.

Bad input

Non-numeric ReadLine

Convert.ToInt32 throws — use TryParse.

Large rows

Large row count

Total lines = 2*levels - 1 — grows quadratically with peak height.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Right-aligned triangle

2. Top half only

  • Print only i = 1..levels without the mirror
  • See how the growing half works alone

3. Next in series

  • Continue with Program 45
  • Next pattern in the number-pattern series

4. Descending digits

  • Print k from 2*i-1 down to 1
  • Same space loops, reversed number loop

Notes

  • Loop rule. Top i = 1..levels, space loop then k = 1..2*i-1. Bottom starts at levels - 1.
  • Console.Write stays on the line; WriteLine advances — mix them carefully.
  • Validate levels > 0 for interactive programs; levels = 1 prints a single centered 1.
  • Bottom half starts at levels - 1 — do not repeat the peak row at i = levels.

Quick Takeaway: top loop i = 1..levels, space loop then digits k = 1..2*i-1, bottom i = levels-1..1, then WriteLine().

⏱️ 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 centered number diamond is a compact lesson in symmetric patterns and centering spaces: print leading spaces, print digits 1 to 2*i-1, grow rows in the top half, then mirror back down. Master the fixed-levels version, then try user input and a smaller trace demo.

Practice the three examples above, then continue to Program 45 for the next pattern in the series.

Bottom half must start at levels - 1 — validate levels when reading from the console.

💡 Best Practices

✅ Do

  • Use top loop for (i = 1; i <= levels; i++)
  • Bottom loop for (i = levels - 1; i >= 1; i--)
  • Spaces then digits: Console.Write(k) for k = 1..2*i-1
  • Prefer int.TryParse over bare Convert.ToInt32
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call WriteLine inside the inner loop
  • Start bottom loop at i = levels (repeats peak row)
  • Use k <= i * 2 instead of k < i * 2
  • Skip the space loop (breaks centering)
  • Ignore bad console input in user-facing demos
  • Skip the levels = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this number diamond

Print the pattern the beginner-friendly way.

5
Core concepts
02

Two halves

Top + mirror

Code
% 03

Row width

2*i-1 digits

Code
04

Bottom start

i = levels-1

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

A centered diamond of ascending digit sequences: 1, 123, 12345, 1234567, 123456789, then mirrors back down to 1.
The row prints 2*i-1 digits (odd length): 1, 3, 5, 7, 9, ... using for (k = 1; k < i*2; k++).
A space loop prints leading spaces before the numbers. Top half uses for (j = i; j < levels; j++); bottom half uses for (j = levels; j > i; j--).
The first loop builds the top half (i = 1..levels). The second mirrors back down (i = levels-1..1) to complete the diamond.
Program 43 is a right-aligned triangle with fixed-width columns. Program 44 is a symmetric centered diamond with odd-length digit rows.
Replace 5 with a levels variable in both outer loops and space bounds — see Example 2.
O(n²) for n levels because each level prints O(n) digits and there are O(n) levels.
Prefer int.TryParse(Console.ReadLine(), out levels) so bad input does not throw FormatException.
Only one row prints — a single centered 1.

Did you Know? 🔊

This pattern prints a top half (1..levels) and a bottom half (levels-1..1). Each row prints 2*i-1 digits (1 to 2*i-1) with leading spaces to center the diamond.

Continue to Program 45

Move on to the next pattern in the C# number-pattern series.

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