Number-Star Diamond Pattern in C#

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

What You’ll Learn

The number-star diamond prints 1, 2*2, 3*3*3, … 5*5*5*5*5, then mirrors back down — a natural step after the right-aligned triangle in Program 30. This tutorial covers two outer loops, modulus alternation, a live preview, worked C# examples, edge cases, and complexity.

Shape Rule

Diamond halves

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

Top Loop

i = 1..n

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

Bottom Loop

i = n-1..1

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

Modulo (j % 2)

Alternate fill

Odd j prints i; even j prints *.

Live Preview

Height 3–7

Pick a height and draw the number-star diamond in the browser.

O(n²)

Complexity

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

Introduction

A number-star diamond pattern alternates the row number and * on each line, growing to a peak then mirroring back down. With n = 5, you get 1, 2*2, … 5*5*5*5*5, then the same rows in reverse.

In C# you use two outer loops (top and bottom halves) and j % 2 inside the inner loop to alternate digit and star.

Why it matters?

It combines symmetric diamond logic with the modulus operator — a step up from Program 30’s single-loop triangle.

Key Highlights

2*i-1 chars

Inner loop runs j < i*2.

j % 2

Odd prints i, even prints *.

Two halves

Top 1..n, bottom n-1..1.

Series Foundation

Follow Program 30; continue to Program 32 (triangle from 11) next.

In short: top loop i = 1..n, bottom loop i = n-1..1, inner j % 2 alternates digit and star, then WriteLine().

📝 Problem & Approach

Given n = 5, print a number-star diamond: top half i = 1..n, bottom half i = n-1..1, each row alternating digit i and * via j % 2.

C#
// n = 5 (conceptual shape)
// 1
// 2*2
// 3*3*3
// 4*4*4*4
// 5*5*5*5*5
// 4*4*4*4
// 3*3*3
// 2*2
// 1

Inputs & Outputs

ItemTypeDescription
nintDiamond peak height — total lines = 2*n - 1.
iintOuter loop — current row number printed on odd positions.
jintInner loop — j % 2 == 0 prints *, else prints i.

Minimal workflow

Pseudocode
for i from 1 to n:
    for j from 1 to i*2 - 1:
        if j % 2 == 0: print *
        else: print i
    print newline
for i from n-1 down to 1:
    for j from 1 to i*2 - 1:
        if j % 2 == 0: print *
        else: print i
    print newline

Approach comparison

ApproachIdeaBest for
if/else1, 2*2, 3*3*3, …Learning and interviews
Ternary operator(j % 2 == 0) ? "*" : i.ToString()Compact console programs
User-input nint n = Convert.ToInt32(...)Flexible diamond height

⚡ Quick Reference

GoalPattern
Top halffor (i = 1; i <= n; i++)
Bottom halffor (i = n - 1; i >= 1; i--)
Inner loopfor (j = 1; j < i * 2; j++)
Alternate fillif (j % 2 == 0) Console.Write("*"); else Console.Write(i);
Ternary formConsole.Write((j % 2 == 0) ? "*" : i.ToString());
User inputint n = Convert.ToInt32(Console.ReadLine());

📋 if/else vs Ternary vs User Input

Same number-star diamond — different ways to write the modulus check and control height.

Top half
i = 1..n

Growing rows to the peak

Bottom half
i = n-1..1

Mirror back down

Modulo
j%2==0 ? * : i

Alternate star and digit

Learning tip
2*i-1

Characters per row

Context

When This Pattern Shows Up

Reach for this pattern when teaching symmetric diamonds, the modulus operator, and two-phase loop structures.

  1. Post triangle exercise

    Natural follow-up after Program 30 — introduces modulus 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 30 (right-aligned triangle) and Program 32 (triangle from 11) 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 7 and draw the number-star diamond in the browser.

Try 3, 5, or 7. Max up to 7 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 full diamond with n = 5 using if/else and j % 2.

Example 1 — Fixed n = 5

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

C#
using System;

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

            for (i = 1; i <= 5; i++)
            {
                for (j = 1; j < i * 2; j++)
                {
                    if (j % 2 == 0)
                        Console.Write("*");
                    else
                        Console.Write(i);
                }
                Console.WriteLine();
            }

            for (i = 4; i >= 1; i--)
            {
                for (j = 1; j < i * 2; j++)
                {
                    if (j % 2 == 0)
                        Console.Write("*");
                    else
                        Console.Write(i);
                }
                Console.WriteLine();
            }
        }
    }
}

How It Works

When i = 1, the inner loop prints one character — 1. When i = 3, it prints 3*3*3 (five characters). The bottom half mirrors from i = 4 down to 1.

📈 User Input

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

Example 2 — User Input

Read n from the console to control diamond height.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter n: ");
            int n = Convert.ToInt32(Console.ReadLine());
            if (n < 1) return;

            for (int i = 1; i <= n; i++)
            {
                for (int j = 1; j < i * 2; j++)
                    Console.Write((j % 2 == 0) ? "*" : i.ToString());
                Console.WriteLine();
            }

            for (int i = n - 1; i >= 1; i--)
            {
                for (int j = 1; j < i * 2; j++)
                    Console.Write((j % 2 == 0) ? "*" : i.ToString());
                Console.WriteLine();
            }
        }
    }
}

How It Works

Same diamond core as Example 1; a ternary operator replaces if/else and n replaces hard-coded 5.

⚡ Smaller Demo

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

Example 3 — Compact n = 3

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

C#
using System;

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

            for (int i = 1; i <= n; i++)
            {
                for (int j = 1; j < i * 2; j++)
                {
                    if (j % 2 == 0) Console.Write("*");
                    else Console.Write(i);
                }
                Console.WriteLine();
            }

            for (int i = n - 1; i >= 1; i--)
            {
                for (int j = 1; j < i * 2; j++)
                {
                    if (j % 2 == 0) Console.Write("*");
                    else Console.Write(i);
                }
                Console.WriteLine();
            }
        }
    }
}

How It Works

Only n changes from 5 to 3 — the if/else and two-loop structure 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 with n = 5.

Setup
2

Top half

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

Top
3

Inner loop (j)

for (j = 1; j < i * 2; j++) — prints 2*i-1 characters per row.

Width
4

Modulo alternation

j % 2 == 0 prints *; odd j prints i.

Fill
5

Bottom half

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

Mirror
=

Number-star diamond complete

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

🔎 Worked Walkthrough — top half n = 5

Trace each outer-loop value of i, inner-loop range, character count, and full row output.

iInner range (j)CharsRow output
1111
21, 2, 332*2
31..553*3*3
41..774*4*4*4
51..995*5*5*5*5

Characters per row = 2*i-1. 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: flip j % 2 logic and watch stars land on wrong positions.

2. Pattern Series Base

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

Example: continue to Program 32 for a triangle starting from 11.

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(j + " ") between digits for wider spacing.

5. Complexity Intuition

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

Example: count printed characters for n = 5 — top half alone prints 25 chars.

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 and j on paper for n = 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 j % 2 on Paper

    Mark odd/even positions for each row before coding the alternation.

  5. 5. Dry-Run n = 3

    Trace i = 1..3 on paper before coding the full n = 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 number-star 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(i) or Write("*"); WriteLine only after the inner loop.

  2. 2. Flipping Modulo Logic

    Using j % 2 != 0 for stars (instead of == 0) swaps digit and star positions.

    → Even j prints *; odd j prints i.

  3. 3. Wrong Inner Bound

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

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

  4. 4. Repeating the Peak Row

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

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

  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.

n = 1

Single row diamond

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

n = 0

Empty pattern

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

Negative

n < 0

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

n = 2

Smallest diamond

Three rows: 1, 2*2, 1.

Bad input

Non-numeric ReadLine

Convert.ToInt32 throws — use TryParse.

Large rows

Large row count

Total lines = 2*n - 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..n without the mirror
  • See how the growing half works alone

3. Triangle from 11

  • Continue with Program 32
  • Formula-based increasing triangle

4. Swap fill character

  • Replace * with # or .
  • Same j % 2 logic, different symbol

Notes

  • Modulo rule. Odd j prints i; even j prints *. Inner loop runs j < i*2.
  • Console.Write stays on the line; WriteLine advances — mix them carefully.
  • Validate n > 0 for interactive programs; n = 1 prints a single 1.
  • Bottom half starts at n - 1 — do not repeat the peak row at i = n.

Quick Takeaway: top loop i = 1..n, bottom i = n-1..1, inner j % 2 alternates digit and star, 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 number-star diamond is a compact lesson in symmetric patterns and the modulus operator: alternate i and * with j % 2, grow rows in the top half, then mirror back down. Master the fixed-n version, then try user input and a smaller trace demo.

Practice the three examples above, then continue to Program 32 for the increasing number triangle starting from 11.

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

💡 Best Practices

✅ Do

  • Use top loop for (i = 1; i <= n; i++)
  • Bottom loop for (i = n - 1; i >= 1; i--)
  • Inner: j % 2 == 0 prints *, else prints i
  • 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 = n (repeats peak row)
  • Use j <= i * 2 instead of j < i * 2
  • Flip the modulo condition
  • Ignore bad console input in user-facing demos
  • Skip the n = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this number-star diamond

Print the pattern the beginner-friendly way.

5
Core concepts
02

Two halves

Top + mirror

Code
% 03

Row width

2*i-1 chars

Code
04

Bottom start

i = n-1

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The inner loop runs while j < i*2, which prints 1, 3, 5, 7, 9 characters for i = 1..5.
It checks j % 2. Even j prints '*', odd j prints the current row number i.
The first loop builds the top half (i = 1..n). The second mirrors back down (i = n-1..1) to complete the diamond.
Program 30 is a right-aligned descending triangle. Program 31 alternates digits and stars in a symmetric diamond shape.
Replace 5 with n in both outer loops — see Example 2.
O(n²) for n rows because total printed characters grow quadratically across both halves.
Prefer int.TryParse(Console.ReadLine(), out n) so bad input does not throw FormatException.
Only one row prints — a single 1.
Yes — Console.Write((j % 2 == 0) ? "*" : i.ToString()) compacts the if/else logic.

Did you Know? 🔊

This pattern prints a top half (1..n) and a bottom half (n-1..1). Each row prints 2*i-1 characters, alternating the row number and * using j % 2.

Continue to Program 32

Move on to the increasing number triangle starting from 11 in the C# number-pattern series.

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