Filled Diamond Star Pattern in C

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
2*i - 1 stars

What You’ll Learn

A filled diamond is a center-aligned pyramid stacked with its mirror: spaces for centering, odd star counts for symmetry, and a lower half that starts at rows - 1. This tutorial covers the shape rule, both halves, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Shape Rule

Pyramid + mirror

Grow to 2*rows-1 stars, then shrink back to 1 — solid stars every row.

Leading Spaces

rows - i

Center each row with rows - i spaces before the stars.

Odd Star Runs

2*i - 1

Print 1, 3, 5, … stars so every row has a single center.

No Duplicate Peak

Start at rows - 1

Lower half begins below rows so the widest line prints once.

Live Preview

1–12 rows

Pick a half-height and draw the solid diamond in the browser.

O(n²)

Complexity

2n - 1 lines, each Θ(n) work — overall O(n²), O(1) extra space.

Introduction

A filled diamond is a solid, center-aligned diamond of * characters. You build it by printing a centered pyramid for i = 1rows, then the same row formula with i running from rows - 1 down to 1.

Unlike the hollow diamond (Program 9), every position in the star segment is filled. Tip rows are shorter; the middle row has 2 * rows - 1 stars and no leading spaces when i == rows.

Why it matters?

It stitches two earlier skills — Program 5’s pyramid and reverse outer iteration — into one figure. Once this clicks, hollow and framed diamonds are smaller jumps.

Key Highlights

Two Phases

Upper 1..rows, then lower rows-1..1.

Same Inners

Spaces then odd star runs — reused in both halves.

Odd Widths

2*i - 1 keeps a centered peak each row.

Solid Fill

Full star segments — not an outline like Program 9.

In short: for each half, print rows - i spaces and 2 * i - 1 stars; grow i to rows, then shrink from rows - 1 to 1.

📝 Problem & Approach

Given a positive integer rows (half-height of the diamond), print a solid center-aligned diamond with 2 * rows - 1 lines.

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

Inputs & Outputs

ItemTypeDescription
rowsintHalf-height (number of rows in the upper pyramid, typically ≥ 1).
Printed outputtext2 * rows - 1 centered lines; row formula uses spaces + odd star runs.

Minimal workflow

Pseudocode
for i from 1 to rows:          // upper half
    print (rows - i) spaces
    print (2 * i - 1) stars
    newline

for i from rows - 1 down to 1: // lower half
    print (rows - i) spaces
    print (2 * i - 1) stars
    newline

Approach comparison

ApproachIdeaBest for
Two outer loopsUpper grow + lower shrink, shared innersLearning and interviews
print_row helperBuild spaces and stars as stringsShorter demos after loops click

⚡ Quick Reference

GoalPattern
Leading spacesfor (j = 1; j <= rows - i; j++) printf(" ");
Star runfor (k = 1; k <= 2 * i - 1; k++) printf("*");
Upper halffor (i = 1; i <= rows; i++)
Lower halffor (i = rows - 1; i >= 1; i--)
Total lines2 * rows - 1
Widest stars2 * rows - 1 (when i == rows)

📋 Filled vs Hollow vs Pyramid Alone

Same family of patterns — different fill and loop range.

This page
solid diamond

Full 2*i-1 star runs; tip rows shorter

Program 9
hollow outline

Diagonal stars only; fixed width 2*rows-1

Program 5
upper only

Same inners as this page’s first half

Interview tip
say both halves

Explain grow then shrink — and why skip i == rows twice

Context

When This Pattern Shows Up

Reach for a filled diamond when combining centering with a grow-then-shrink outer sequence.

  1. After pyramids

    Natural next step once Program 5’s centered triangle is solid.

  2. Two-phase loop drills

    Practice ascending then descending outer bounds with shared inners.

  3. Symmetry checks

    Odd star counts and matching space formulas teach left–right balance.

  4. Gateway to hollow / framed

    Programs 9 and 11 reuse the two-phase idea with different fill rules.

  5. Not a graphics API

    Terminal teaching pattern — not how you draw diamonds in UI frameworks.

Key benefit: one figure that combines centering, odd widths, and careful outer-loop sequencing without duplicate middle rows.

🔮 Live Preview

Choose a half-height between 1 and 12 and draw the filled diamond in the browser.

Try 4, 5, or 7. Total printed lines will be 2 * rows - 1.

Live result
Press "Draw diamond".

Examples Gallery

Three complete C programs — fixed half-height, console input, and a print_row helper. Click View Output to reveal sample console results.

📚 Getting Started

Print a diamond with half-height 5 using classic nested loops.

Example 1 — Fixed rows = 5

Same j / k inner loops as Program 5, plus the mirrored lower half.

c
#include <stdio.h>

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

    /* Upper half */
    for (i = 1; i <= rows; ++i) {
        for (j = 1; j <= rows - i; ++j) {
            printf(" ");
        }
        for (k = 1; k <= 2 * i - 1; ++k) {
            printf("*");
        }
        printf("\n");
    }

    /* Lower half (no duplicate widest row) */
    for (i = rows - 1; i >= 1; --i) {
        for (j = 1; j <= rows - i; ++j) {
            printf(" ");
        }
        for (k = 1; k <= 2 * i - 1; ++k) {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}

How It Works

Upper i grows from 1 to 5: spaces shrink, stars grow 1, 3, 5, 7, 9. Lower i shrinks from 4 to 1: spaces grow, stars shrink 7, 5, 3, 1 — closing the diamond without reprinting the middle row.

📈 Practical Variant

Let the user choose the half-height 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 i, j, k;

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

    for (i = 1; i <= rows; ++i) {
        for (j = 1; j <= rows - i; ++j) {
            printf(" ");
        }
        for (k = 1; k <= 2 * i - 1; ++k) {
            printf("*");
        }
        printf("\n");
    }

    for (i = rows - 1; i >= 1; --i) {
        for (j = 1; j <= rows - i; ++j) {
            printf(" ");
        }
        for (k = 1; k <= 2 * i - 1; ++k) {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}

How It Works

Same two-phase core as Example 1; only the source of rows changes. Non-numeric input leaves rows unset if you ignore scanf’s return value — always check it in safer labs.

⚡ Shortcut Style

Same diamond with a reusable print_row helper.

Example 3 — print_row Helper

Encode the shared space/star formula once; both outer loops call it.

c
#include <stdio.h>

void print_row(int rows, int i) {
    int j, k;
    for (j = 1; j <= rows - i; ++j) {
        putchar(' ');
    }
    for (k = 1; k <= 2 * i - 1; ++k) {
        putchar('*');
    }
    putchar('\n');
}

int main(void) {
    int rows = 5;
    int i;

    for (i = 1; i <= rows; ++i) {
        print_row(rows, i);
    }

    for (i = rows - 1; i >= 1; --i) {
        print_row(rows, i);
    }

    return 0;
}

How It Works

print_row encodes the shared formula once; both outer loops call it. Great after you understand the nested-loop version — keep the explicit j/k loops for exams that want both bounds visible.

🧠 How the Algorithm Prints the Diamond

1

Upper half (i = 1rows)

Print rows - i spaces, then 2 * i - 1 stars, then a newline. Star counts: 1, 3, 5, …, 2*rows-1.

Pyramid
2

Lower half (i = rows - 11)

Reuse the same two inner loops. As i shrinks, spaces grow and stars shrink — for rows = 5: 7, 5, 3, 1.

Mirror
3

Why 2 * i - 1?

Odd widths keep a single center star. Growing by two stars per step adds one on each side and preserves symmetry.

Odd counts
4

New line every row

printf("\n") after the star loop ends each diamond line in both phases.

Line break
=

Solid diamond

2 * rows - 1 lines; widest line has 2 * rows - 1 stars. O(n²) for n = rows, O(1) extra space.

🔎 Worked Walkthrough — rows = 4

Trace each outer-loop i: spaces, stars, and which half produced the line.

HalfiSpaces rows - iStars 2*i - 1Printed row
Upper131   *
Upper223  ***
Upper315 *****
Upper407*******
Lower315 *****
Lower223  ***
Lower131   *

Total lines: 2 × 4 - 1 = 7. The widest row (i = 4) appears only in the upper half.

Use Cases

Where this diamond (and its two-phase loop structure) shows up beyond the homework prompt.

1. Combining Prior Patterns

Prove you can reuse Program 5’s row body in a second phase.

Example: extract a print_row(rows, i) helper.

2. Symmetry Practice

Odd widths and matching margins train left–right balance.

Example: swap to i stars and watch centering break.

3. Off-by-One Awareness

Starting lower at rows duplicates the peak — a classic bug.

Example: set lower start to rows and compare output.

4. Character Substitution

Swap * for digits or letters once the geometry works.

Example: print i inside the star run for a number diamond.

5. Contrast With Hollow

Solid fill vs outline (Program 9) clarifies why inner logic differs.

Example: side-by-side outputs for the same rows.

6. Complexity Intuition

2n-1 lines of Θ(n) work make O(n²) concrete.

Example: count printed characters for n = 5.

Pro Tip: in interviews, say “upper pyramid, then mirror from rows-1” before writing loops — that sequence is the whole design.

Advantages

Why this solid-diamond approach is a favorite teaching pattern.

  1. 1. Reuses Known Building Blocks

    Same space/star formulas as Program 5 — only the outer sequence changes.

  2. 2. Clear Visual Symmetry

    Odd star counts make centering errors obvious immediately.

  3. 3. Easy to Factor

    One print_row helper serves both outer loops cleanly.

  4. 4. O(1) Extra Memory

    Streaming console output needs only loop counters.

Pro Tip: master the nested-loop version first; treat print_row as a polish shortcut afterward.

Usage Tips

Small habits that keep filled-diamond code clean.

  1. 1. Extract the Row Formula

    Spaces + stars + newline belong in one place so both halves stay identical.

  2. 2. Start Lower at rows - 1

    Never start the mirror at rows unless you want a doubled middle line.

  3. 3. Keep 2 * i - 1

    Using i stars alone breaks centered diamond symmetry.

  4. 4. Check scanf’s return value

    Always check that scanf returns 1 when reading interactive row counts.

  5. 5. Dry-Run a Small n

    Trace rows = 3 or 4 on paper before coding larger demos.

Pro Tip: if the middle row appears twice, your lower loop almost certainly started at i = rows.

Common Pitfalls

Mistakes that commonly break filled diamond patterns.

  1. 1. Lower Half Starts at rows

    The widest line prints twice and the diamond looks “fat” in the middle.

    → Start the second outer loop at rows - 1.

  2. 2. Using i Stars Instead of 2*i - 1

    You get a left-leaning or uneven shape, not a centered diamond.

    → Keep odd star counts: 2 * i - 1.

  3. 3. Confusing With Program 9

    Hollow diamonds need different inner logic and fixed line width — not a one-line tweak.

    → Use Program 9 for outlines.

  4. 4. Wrong Space Count

    rows - i + 1 or i spaces shifts the whole figure off-center.

    → Leading spaces are exactly rows - i.

  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

Single star

Upper prints *; lower loop does not run — output is one line.

rows = 0

Empty pattern

Both halves skip — print nothing or show a validation message.

Negative

rows < 0

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

Large n

Wide middle row

Middle width is 2*n-1 stars — fine for labs; wrap or scroll on tiny terminals.

Bad input

Non-numeric scanf

Failed scanf leaves rows unset — check its return value.

Half-height

rows meaning

Confirm whether the prompt means half-height or total lines (2n-1).

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Print upper half only

  • Drop the second outer loop
  • You should match Program 5

2. Hollow diamond next

  • Keep two phases; change fill to outline
  • Compare with Program 9

3. Safe input loop

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

4. Number diamond

  • Replace * with digits or i
  • Shows the geometry is independent of the fill character

Notes

  • Line count. Total lines are 2 * rows - 1; widest stars are also 2 * rows - 1.
  • Row character count before newline is (rows - i) + (2*i - 1) = rows + i - 1 — tip rows are shorter than the middle.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single star.
  • Hollow and framed variants reuse the two-phase idea but change how each row is filled.

Quick Takeaway: spaces = rows - i, stars = 2*i - 1, grow then shrink from rows - 1 — that is the filled diamond.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
print_row helper (Example 3)O(rows²)O(rows) temporary per row string

About 2 * rows - 1 lines; each line does Θ(rows) work for spaces and stars combined.

Wrap Up

🎉 Conclusion

The filled diamond is a centered pyramid plus its mirror: shared rows - i spaces and 2 * i - 1 stars, with the lower half starting at rows - 1 so the peak prints once. Master that two-phase story and hollow or framed diamonds become incremental changes.

Practice the three examples above, then continue to the diamond-in-square pattern for a framed follow-up.

Grow to rows, shrink from rows - 1, keep odd star runs — and validate half-height when reading input.

💡 Best Practices

✅ Do

  • Explain upper grow then lower shrink before coding
  • Use rows - i spaces and 2 * i - 1 stars
  • Start the lower half at rows - 1
  • Check scanf’s return value for interactive demos
  • State O(n²) time when asked about complexity

❌ Don’t

  • Start the lower loop at i == rows
  • Use i stars when you need a centered diamond
  • Confuse this solid fill with Program 9’s hollow outline
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about the filled diamond

Print the solid diamond the beginner-friendly way.

5
Core concepts
02

Spaces

rows - i

Formula
* 03

Stars

2*i - 1

Formula
1 04

Peak once

Lower from rows-1

Gotcha
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The first outer loop runs i from 1 to rows. On each row it prints (rows - i) spaces, then (2 * i - 1) stars. That builds the upper centered pyramid. The second outer loop runs i from (rows - 1) down to 1 with the same two inner loops, mirroring the shape so the diamond closes.
The first part already prints the widest row when i equals rows. Starting the second part at rows - 1 continues with the next narrower rows without repeating the middle line.
The filled diamond prints full runs of stars using 2*i-1 stars per row. The hollow diamond uses diagonal conditions so only the outline has stars. Both use an upper phase and a lower phase starting at rows - 1.
Odd widths keep a single center star on each row and grow by one star on each side per step, which keeps left–right symmetry.
With n equal to rows, there are about 2n - 1 printed rows. Each row does Theta(n) work for spaces and stars combined, so overall time is O(n²).
Exactly 2 * rows - 1 lines. The widest line has 2 * rows - 1 stars.
Yes. Upper half is Program 5; lower half uses the same inner loops with i running like Program 6’s inverted idea, but starting at rows - 1.
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? 🔊

The filled diamond is Program 5’s pyramid plus its mirror: same (rows - i) spaces and (2 * i - 1) stars, with the lower half starting at rows - 1 so the widest row prints only once.

Continue to Diamond in Square

Frame a hollow diamond inside solid top and bottom rows for Program 11.

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