Hollow Diamond Inside Square Star Pattern in C

Beginner
⏱️ 11 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
2n × 2n−1

What You’ll Learn

This pattern frames a hollow diamond inside solid top and bottom bars: fixed width 2 * rows, height 2 * rows - 1, and mirrored middle rows built from left stars, a gap, and right stars. This tutorial covers the grid size, border vs inner logic, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Grid Size

2n × 2n−1

Width 2 * rows, height 2 * rows - 1 — a wide frame for the diamond.

Solid Bars

Top & bottom

First and last lines are full runs of * with no interior gap.

Left / Gap / Right

Inner rows

Equal star blocks on both sides with a hollow gap between them.

Mirrored i

Symmetry

Map each line to i so the gap grows to the waist, then shrinks.

Live Preview

1–10 rows

Pick a size and draw the framed hollow diamond in the browser.

O(n²)

Complexity

2n-1 lines × 2n columns — O(n²) time, O(1) extra space.

Introduction

A hollow diamond inside a square is a framed console figure: solid star bars on the first and last lines, and a hollow diamond carved through the middle rows.

Unlike Program 9 (standalone hollow diamond) or Program 10 (filled diamond), every line here is exactly 2 * rows characters wide, and middle rows are built as left stars + gap + right stars.

Why it matters?

It trains fixed-width grids, border special cases, and mirrored indices in one figure — a strong capstone after simpler triangles and diamonds.

Key Highlights

Fixed Width

Every line is 2 * rows characters.

Solid Caps

Top and bottom bars close the “square” frame.

Three Segments

Left stars, hollow gap, right stars.

Mirrored Index

i grows then shrinks with line position.

In short: solid bars on the ends; elsewhere print left stars, gap spaces, left stars — with i mirrored so the hollow diamond opens and closes.

📝 Problem & Approach

Given a positive integer rows, print a framed hollow diamond with width 2 * rows and height 2 * rows - 1.

c
// rows = 5 (conceptual shape; spaces shown as ·)
// **********
// ****··****
// ***····***
// **······**
// *········*
// **······**
// ***····***
// ****··****
// **********

Inputs & Outputs

ItemTypeDescription
rowsintSize parameter (typically ≥ 1). Controls both width and height.
Printed outputtext2*rows-1 lines, each exactly 2*rows characters before the newline.

Minimal workflow

Pseudocode
height = 2 * rows - 1
width  = 2 * rows

for line from 1 to height:
    if line is first or last:
        print width stars
    else:
        i = line if line <= rows else (2 * rows - line)
        left = rows - i + 1
        gap  = 2 * (i - 1)
        print left stars, gap spaces, left stars
    newline

Approach comparison

ApproachIdeaBest for
Three-segment loopsLeft / gap / right on inner rowsLearning and interviews
print_chars helperBuild each segment as a stringShorter demos after formulas click

⚡ Quick Reference

GoalPattern
Dimensionsheight = 2 * rows - 1, width = 2 * rows
Solid barif (line == 1 || line == height) print width stars
Map line → ii = (line <= rows) ? line : (2 * rows - line)
Left / right starsleft = rows - i + 1
Hollow gapgap = 2 * (i - 1)
Width check2 * left + gap == width

📋 Program 11 vs 9 vs 10

Three diamond-related patterns — different frames and fills.

This page
framed hollow

Solid bars + left/gap/right; width 2n

Program 9
hollow alone

Outline only; fixed width 2n-1 per line

Program 10
solid diamond

Full star runs; tip rows shorter than middle

Interview tip
state dimensions

Say width/height first, then border vs inner cases

Context

When This Pattern Shows Up

Reach for this figure when you need a fixed-width frame with a hollow diamond interior.

  1. Capstone pattern labs

    Often the last numbered exercise after triangles and diamonds.

  2. Fixed-width grid drills

    Every line must close at the same column count.

  3. Border vs interior logic

    Special-case first/last rows; formula-drive the middle.

  4. Symmetry mapping

    Practice folding a line index into a mirrored i.

  5. Not a UI layout tool

    Terminal teaching pattern — not how you build framed widgets in apps.

Key benefit: one pattern that combines dimensions, border cases, segment math, and mirrored indices.

🔮 Live Preview

Choose a size between 1 and 10 and draw the framed hollow diamond in the browser.

Try 4, 5, or 6. Width will be 2 * rows; height 2 * rows - 1.

Live result
Press "Draw pattern".

Examples Gallery

Three complete C programs — fixed size, console input, and a print_chars helper. Click View Output to reveal sample console results.

📚 Getting Started

Print the classic rows = 5 framed diamond with nested loops.

Example 1 — Fixed rows = 5

Solid bars on the ends; left / gap / right on every other line.

c
#include <stdio.h>

int main(void) {
    int rows = 5;
    int line, j;
    int height = 2 * rows - 1;
    int width = 2 * rows;

    for (line = 1; line <= height; ++line) {
        if (line == 1 || line == height) {
            for (j = 1; j <= width; ++j) {
                printf("*");
            }
        } else {
            int i = (line <= rows) ? line : (2 * rows - line);
            int left = rows - i + 1;
            int gap = 2 * (i - 1);

            for (j = 1; j <= left; ++j) {
                printf("*");
            }
            for (j = 1; j <= gap; ++j) {
                printf(" ");
            }
            for (j = 1; j <= left; ++j) {
                printf("*");
            }
        }
        printf("\n");
    }

    return 0;
}

How It Works

Lines 1 and 9 are solid 10-star bars. On line 5 (the waist), i = 5, so left = 1 and gap = 8 — a single star on each side with a wide hollow center. Lines above and below mirror that formula via the ternary for i.

📈 Practical Variant

Let the user choose the size at runtime.

Example 2 — User Input Version

Read rows with scanf("%d", &rows) (check the return value in real apps).

c
#include <stdio.h>

int main(void) {
    int rows;
    int line, j;
    int height, width;

    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    height = 2 * rows - 1;
    width = 2 * rows;

    for (line = 1; line <= height; ++line) {
        if (line == 1 || line == height) {
            for (j = 1; j <= width; ++j) {
                printf("*");
            }
        } else {
            int i = (line <= rows) ? line : (2 * rows - line);
            int left = rows - i + 1;
            int gap = 2 * (i - 1);

            for (j = 1; j <= left; ++j) {
                printf("*");
            }
            for (j = 1; j <= gap; ++j) {
                printf(" ");
            }
            for (j = 1; j <= left; ++j) {
                printf("*");
            }
        }
        printf("\n");
    }

    return 0;
}

How It Works

Same grid logic as Example 1; only the source of rows changes. For rows = 4 you get 7 lines × 8 columns. Non-numeric input leaves rows unset if you ignore scanf’s return value — always check it in safer labs.

⚡ Shortcut Style

Same figure with a reusable print_chars helper for each segment.

Example 3 — print_chars Helper

Encode each segment once with print_chars; the outer loop only picks counts.

c
#include <stdio.h>

void print_chars(char ch, int n) {
    int j;
    for (j = 1; j <= n; ++j) {
        putchar(ch);
    }
}

int main(void) {
    int rows = 5;
    int line;
    int height = 2 * rows - 1;
    int width = 2 * rows;

    for (line = 1; line <= height; ++line) {
        if (line == 1 || line == height) {
            print_chars('*', width);
            putchar('\n');
        } else {
            int i = (line <= rows) ? line : (2 * rows - line);
            int left = rows - i + 1;
            int gap = 2 * (i - 1);

            print_chars('*', left);
            print_chars(' ', gap);
            print_chars('*', left);
            putchar('\n');
        }
    }

    return 0;
}

How It Works

Same formulas as Example 1; print_chars replaces the three inner loops. Keep the loop version for exams that want every bound visible.

🧠 How the Algorithm Prints the Frame

1

Grid size

height = 2 * rows - 1 lines; width = 2 * rows characters per line. For rows = 4: 7 × 8.

Dimensions
2

Top and bottom bars

When line == 1 or line == height, print a solid run of width stars — the closed horizontal edges.

Border
3

Inner rows: left, gap, right

Map linei, then left = rows - i + 1 and gap = 2 * (i - 1). Print left stars, gap spaces, left stars again.

Symmetry
4

Finish each line

printf("\n") after the bar or the three segments. Every line is exactly width characters before the newline.

Line break
=

Hollow center

O(n²) for n = rows (2n-1 lines × up to 2n cells), O(1) extra space.

🔎 Worked Walkthrough — rows = 4

Trace each line: whether it is a solid bar, and if not, the values of i, left, and gap.

lineKindileftgapPrinted row
1Bar********
2Inner232***  ***
3Inner324**    **
4Inner416*      *
5Inner324**    **
6Inner232***  ***
7Bar********

Check: on every inner row, 2 * left + gap = 8 = width. Lines 3 and 5 share the same i because of mirroring.

Use Cases

Where this framed hollow diamond (and its grid thinking) shows up beyond the homework prompt.

1. Capstone Nested Loops

Combines borders, segments, and mirroring in one program.

Example: final lab after Programs 9 and 10.

2. Width Invariant Checks

Assert 2*left + gap == width while debugging.

Example: print lengths before printf("\n").

3. Contrast Pattern Families

Side-by-side with Program 9 shows why structures differ.

Example: same rows, different width rules.

4. Single-Loop Rewrite

One loop over columns with border/left/right predicates.

Example: for (j = 1; j <= width; j++) with booleans.

5. Character Themes

Swap border vs interior characters once geometry works.

Example: # on bars, * on sides.

6. Complexity Stories

Fixed-size grids make O(n²) easy to count by hand.

Example: cells = (2n-1)*2n.

Pro Tip: in interviews, state “width 2n, height 2n-1, solid caps, then left/gap/right with mirrored i” before writing a single loop.

Advantages

Why this framed layout is a strong teaching pattern.

  1. 1. Easy Width Check

    2 * left + gap == width catches off-by-one bugs immediately.

  2. 2. Clear Special Cases

    Top/bottom bars are obvious; middle rows share one formula.

  3. 3. One Mirror Formula

    A single ternary for i keeps upper and lower halves in sync.

  4. 4. O(1) Extra Memory

    Streaming output needs only counters and a few ints.

Pro Tip: learn the three-loop segment version first; treat print_chars as a polish shortcut afterward.

Usage Tips

Small habits that keep framed-diamond code clean.

  1. 1. Name Width and Height

    Compute width and height once — do not mix 2*rows and 2*rows-1 by accident.

  2. 2. Handle Bars First

    Special-case top and bottom before writing the inner formula.

  3. 3. Verify the Invariant

    Mentally check 2 * left + gap == width on a middle and a near-tip row.

  4. 4. Check scanf’s return value

    Always check that scanf returns 1 when reading interactive sizes.

  5. 5. Dry-Run rows = 4

    The walkthrough table above catches mirror and gap mistakes fast.

Pro Tip: if a line is shorter or longer than the others, you almost certainly used the wrong formula for left or gap.

Common Pitfalls

Mistakes that commonly break the framed hollow diamond.

  1. 1. Mixing Width and Height

    Using 2*rows-1 as width (or 2*rows as height) skews the whole figure.

    → Width is 2*rows; height is 2*rows-1.

  2. 2. Copying Program 9 Diagonal Logic

    Different coordinate system — i == j style loops will not match this 10-wide picture for rows = 5.

    → Use left / gap / right for this page.

  3. 3. Wrong Mirror Formula

    Forgetting 2 * rows - line breaks lower-half symmetry.

    i = (line <= rows) ? line : (2 * rows - line).

  4. 4. Trailing Extra Spaces

    Padding after the right star block makes lines longer than width.

    → Stop after the second left-star run.

  5. 5. Blind scanf

    Failed scanf leaves rows uninitialized.

    → Check scanf’s return value and require rows >= 1.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Two-star bar

Height = 1, width = 2 — only one solid line ** (first == last).

rows = 2

Minimal frame

3 lines × 4 columns: bar, *  *, bar.

rows = 0

Empty pattern

Loop never runs — validate and re-prompt.

Negative

rows < 0

Treat as invalid; do not print a broken grid.

Large n

Wide bars

Width grows as 2n — fine for labs; may wrap on tiny terminals.

Bad input

Non-numeric scanf

Failed scanf leaves rows unset — check its return value.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 9

  • Print both for the same rows
  • Note width 2n vs 2n-1

2. Single-column loop

  • Rewrite each line as one loop over j = 1..width
  • Decide star vs space with conditions

3. Safe input loop

  • Check scanf returns 1 and re-prompt until rows >= 1
  • Then draw the frame

4. Dual character theme

  • Use one character for bars, another for sides
  • Keep the same lengths and gap

Notes

  • Dimensions. Width 2n, height 2n - 1 for n = rows.
  • Every inner row satisfies 2 * left + gap == width — use that as a sanity check.
  • Validate rows > 0 for interactive programs; rows = 1 collapses to a single two-star bar.
  • This is the last numbered pattern in the C star series — review Programs 9 and 10 for the related diamond family.

Quick Takeaway: solid bars on the ends; elsewhere left stars, hollow gap, right stars — with mirrored i and fixed width 2 * rows.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
print_chars helper (Example 3)O(rows²)O(rows) temporary per segment

About 2 * rows - 1 lines; each prints 2 * rows characters — overall Θ(n²).

Wrap Up

🎉 Conclusion

The hollow diamond inside a square is a fixed-width frame: solid top and bottom bars, and mirrored left / gap / right rows in between. Once the dimensions and the i mapping click, the rest is careful segment printing.

Practice the three examples above, then browse the star-pattern hub to revisit earlier triangles and diamonds.

Width 2n, height 2n-1, solid caps, then left/gap/right with mirrored i — and keep 2*left + gap == width.

💡 Best Practices

✅ Do

  • State width and height before coding
  • Special-case solid top and bottom bars
  • Use mirrored i with left and gap formulas
  • Check 2 * left + gap == width
  • Check scanf’s return value for interactive demos

❌ Don’t

  • Swap 2*rows and 2*rows-1
  • Paste Program 9 diagonal tests into this layout
  • Add trailing spaces after the right star block
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this framed pattern

Print the hollow diamond inside a square the beginner-friendly way.

5
Core concepts
02

Bars

Solid top & bottom

Border
* 03

Segments

Left / gap / right

Inner
04

Mirror

Map line → i

Symmetry
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Use height 2*rows-1 lines and width 2*rows columns. Print a full row of stars on line 1 and on the last line. For every other line, map line to i with symmetry, then print (rows-i+1) stars, a gap of 2*(i-1) spaces, and the same number of stars again.
The classic version uses width 2*rows and height 2*rows-1 so the top and bottom are full horizontal bars while the sides close on the leftmost and rightmost columns of the inner rows.
Program 9 prints a hollow diamond alone with constant width 2*rows-1 and diagonal j/k tests. Program 11 adds solid top and bottom rows of length 2*rows and builds each inner line from left block, gap, and right block.
left = rows - i + 1 is how many stars sit on each side. gap = 2 * (i - 1) is the hollow space between them. Together they always sum to width.
If line <= rows, i = line. Otherwise i = 2 * rows - line. That mirrors the distance from the nearest end so the waist is widest in the gap.
With n equal to rows, there are Theta(n) lines and each line prints Theta(n) characters, so time is O(n²).
Width is 2 * rows, so 10 when rows is 5. Height is 2 * rows - 1, which is 9 lines.
Check scanf's return value: if (scanf("%d", &rows) != 1) handle bad input, and require rows >= 1. Unchecked scanf leaves rows uninitialized on failure.

Did you Know? 🔊

Every line is exactly 2 * rows characters wide. Inner rows always satisfy 2 * left + gap == 2 * rows — so the frame closes cleanly on both sides.

You’ve Reached the Last Numbered Star Pattern

Review Programs 9 and 10, then explore more C topics from the hub.

All C Star Patterns →

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