What are C Number Diamond Patterns- C Programming Course With Examples

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

Free C Programming Course · Control Statements

C Number Diamond Patterns

Build palindromic and mirrored digit diamonds in C – a free C tutorial that sharpens embedded C programming logic

Number Diamond Patterns in C: The Big Idea

Number diamond patterns in C replace the star with digits, and that one change forces you to think about counters that move up and down inside a row. This lecture of our free C programming course shows how to print two classic digit diamonds with plain nested loops. If you are preparing for placements, or working through our free embedded C course to get firmware-ready, these exercises build the loop control you will lean on for lookup tables, ring buffers and display drivers.

What You Will Learn

  • How to print digits instead of stars and keep columns aligned
  • How to make a counter climb to the middle of a row and walk back down
  • Two different number diamond patterns in C with their formulas
  • How to reuse the width-index idea from the star diamond lecture
  • How to debug alignment when numbers have more than one digit

Prerequisites

  • Star pyramid and diamond logic from the previous lecture
  • Nested for loops and the conditional operator
  • Using %d in printf

From Stars to Digits

With stars, every symbol occupies one column. With digits, you must decide how wide a “cell” is. For single-digit numbers (1 to 9) the simplest choice is two columns per cell: the digit and one blank. That means each leading blank in the row also becomes two blanks. Forget this and the diamond leans like a broken fence.

One row = leading cells + rising digits + falling digits
Part 1n – w cells of 2 blanks
Part 2w digits climbing
Part 3w – 1 digits descending
Endnewline

The row width index w is the same trick as before: w = (r <= n) ? r : 2 * n - r. Everything else is a matter of what digit you print.

Palindromic Number Diamond in C

In this pattern every row reads the same forwards and backwards. Row with width w prints 1, 2, … w and then w-1 down to 1. The middle row of a size-4 diamond is 1 2 3 4 3 2 1.

#include <stdio.h>

int main(void)
{
    int n = 4;

    for (int r = 1; r <= 2 * n - 1; r++) {
        int w = (r <= n) ? r : 2 * n - r;

        for (int s = 0; s < n - w; s++)
            printf("  ");                    /* one cell = 2 columns */

        for (int d = 1; d <= w; d++)         /* climb: 1..w */
            printf("%d ", d);

        for (int d = w - 1; d >= 1; d--)     /* descend: w-1..1 */
            printf("%d ", d);

        printf("\n");
    }
    return 0;
}
$ gcc -Wall -std=c11 -o ep_num_diamond1 ep_num_diamond1.c
$ ./ep_num_diamond1
      1
    1 2 1
  1 2 3 2 1
1 2 3 4 3 2 1
  1 2 3 2 1
    1 2 1
      1 

Why It Works

  • The two blank-loop prints give 2 * (n - w) columns, matching the cell width.
  • The climbing loop prints exactly w digits; the descending loop prints w - 1, so the peak digit appears only once.
  • Because both digit loops depend only on w, shrinking rows below the middle mirrors growing rows above.

Mirrored Number Diamond Pattern in C

Now flip the idea: the tips carry the largest digit and the widest row starts at 1. Think of it as “distance from the middle”. A row of width w starts at the value v = n - w + 1 and counts up for w cells, then retraces its steps downward.

#include <stdio.h>

int main(void)
{
    int n = 4;

    for (int r = 1; r <= 2 * n - 1; r++) {
        int w = (r <= n) ? r : 2 * n - r;
        int v = n - w + 1;                   /* first digit of this row */

        for (int s = 0; s < n - w; s++)
            printf("  ");

        for (int k = 0; k < w; k++)          /* v, v+1, ... v+w-1 */
            printf("%d ", v + k);

        for (int k = w - 2; k >= 0; k--)     /* mirror back */
            printf("%d ", v + k);

        printf("\n");
    }
    return 0;
}
$ ./ep_num_diamond2
      4
    3 4 3
  2 3 4 3 2
1 2 3 4 3 2 1
  2 3 4 3 2
    3 4 3
      4 

Comparing the Two Number Diamond Patterns

FeaturePalindromic diamondMirrored diamond
First digit of a rowAlways 1n – w + 1
Peak digit of a rowwn
Tip row (w = 1)1n
Widest row1 2 … n … 2 11 2 … n … 2 1
Extra variable neededNonev (row start)

Notice that both patterns share the same widest row; they only differ in how the shorter rows are filled. That kind of side-by-side comparison is a good habit when you analyse any new pattern.

Choosing the digit formula
Step 1Write the pattern for n = 4
Step 2Find the first digit of each row
Step 3Find the peak digit of each row
Step 4Express both in terms of w and n

Handling Numbers Above 9

If n grows past 9, a digit takes two columns and your 2-column cell breaks. Use a field width in printf, such as %3d, and make each blank cell three spaces. The geometry is the same; only the cell width changes. Define it once:

#define CELL 3

printf("%*s", CELL * (n - w), "");   /* leading blanks in one call */
printf("%*d", CELL, value);           /* every number takes CELL columns */

Here %*s reads the width from the argument list, so one call prints any number of blanks. This is the same technique used to align columns in UART diagnostic logs on embedded boards.

Number Patterns in Embedded C Programming

  • Triangle waves: the climb-then-descend counter is exactly how you generate triangle-wave samples for a DAC or PWM breathing LED.
  • Index mirroring: symmetrical lookup tables (for example a half sine table reused for the other half) rely on mirrored indices.
  • Formatted logs: fixed-width fields keep register dumps readable on a serial terminal.

Common Mistakes and Troubleshooting

SymptomLikely causeFix
Peak digit printed twiceDescending loop starts at w, not w – 1Start the second loop at w – 1
Diamond leans rightBlank cell width does not match digit cell widthUse two blanks per cell for one-digit values
Digits wrong in lower halfWidth index formula not used for rows below the middleUse the conditional expression for w
Output misaligned for n > 9Two-digit numbers need wider cellsUse %3d and three-space cells

Best Practices

  • Name variables by meaning: w for width, v for row start, not a, b, c.
  • Print the intermediate values of w and v for each row when debugging.
  • Keep the pattern size in one variable so tests with n = 1, 2, 5 are one edit away.
  • Prefer one parameterised function over copy-pasted loops for each variant.
Do not trust the first run. Always verify against a hand-drawn n = 3 or n = 4 pattern before moving on. Visual output hides off-by-one bugs until you compare it to the expected shape.

Practice Challenges

  1. Print the palindromic diamond using a descending start (largest digit first in each row).
  2. Add a command-line argument so ./ep_num_diamond1 6 prints a size-6 diamond.
  3. Print only the upper half of the mirrored diamond.
  4. Modify the program to use letters (A, B, C …) instead of digits.

Summary and Key Takeaways

  • Number diamond patterns in C reuse the rows, blanks and width index ideas from star diamonds.
  • Cell width must match between blanks and printed numbers.
  • A climbing loop followed by a descending loop of one fewer element creates a palindromic row.
  • Express the first and peak digits in terms of w and n.

With these two patterns in your toolkit you can decode almost any numeric pyramid. Keep practising in this free C programming course and you will find that tracing nested loops stops feeling mysterious.

Frequently Asked Questions

How do I print a number diamond in C?

Loop 2n – 1 rows, compute a width index per row, print leading blank cells, then a climbing and a descending run of numbers.

Why does my number pattern look crooked?

The blank cell width probably differs from the number cell width. Use the same column count for both.

What does %*d do in printf?

It takes the field width from an argument, letting you choose the column width at run time.

Do I need two outer loops for the upper and lower halves?

No. One loop with a conditional width index handles both halves.

Is this free C tutorial useful for embedded interviews?

Yes. Pattern questions test loop control, which interviewers use to judge fundamentals in embedded C programming roles.

Continue the Free C Programming Course

Next, learn how to find bugs in if-else code, an essential skill for embedded C programming and firmware debugging.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →