How to Star Pyramid Patterns in C- Embedded C Training For Beginners

🚀 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

Star Pyramid Patterns in C

Inverted pyramids and diamonds with nested loops – a free C tutorial for embedded C programming beginners

Why Star Pyramid Patterns in C Matter

Star pyramid patterns in C look like a classroom toy, but they are the cleanest way to learn nested loops. In this free C programming course lecture you will build an inverted pyramid and a full diamond using nothing except for loops and printf. The same row-and-column thinking is used in embedded C programming whenever you fill a framebuffer, drive an LED matrix, or print a formatted table over UART. If you are following our free embedded C course, treat this lecture as a workout for your loop-counting muscles.

What You Will Learn

  • How to split any pattern into rows, leading spaces and stars
  • How to derive a formula for the number of spaces and stars in row r
  • How to print an inverted star pyramid in C
  • How to print a full diamond with a single loop using a width helper
  • Common off-by-one mistakes and how to debug them
  • Why pattern programs matter for C programming for embedded systems

Prerequisites

  • The for loop and nested loops (earlier lectures in this chapter)
  • Basic printf usage from the Input-Output chapter
  • A working GCC setup – any Linux, WSL or MinGW installation is fine

Thinking in Rows, Spaces and Stars

Every text pattern is a rectangle of characters. The terminal prints that rectangle one row at a time, so the outer loop always counts rows. Inside each row you print two kinds of characters: blanks that push the shape to the right, and the visible symbol itself. Each kind needs its own inner loop. After both inner loops finish, one printf("\n") moves to the next row.

Before touching the keyboard, write a small table for your pattern. Pick the row number r (starting from 1) and total rows n. Then record how many blanks and how many stars each row needs. A formula usually jumps out in under a minute.

Anatomy of an inverted pyramid (n = 5)
Row 10 spaces9 stars
Row 21 space7 stars
Row 32 spaces5 stars
Row 43 spaces3 stars
Row 54 spaces1 star
PatternSpaces in row rStars in row rTotal rows
Upright pyramidn – r2r – 1n
Inverted pyramidr – 12(n – r) + 1n
Diamondn – w2w – 12n – 1

In the diamond row, w is the “width index” of that row. It rises from 1 to n and then falls back to 1. You will see how to compute it shortly.

Inverted Star Pyramid in C

The blanks grow by one per row while the stars shrink by two. That gives us the two formulas from the table. Save the following program as ep_inv_pyramid.c.

#include <stdio.h>

int main(void)
{
    int rows = 5;

    for (int r = 1; r <= rows; r++) {
        for (int s = 1; s < r; s++)              /* r - 1 blanks */
            printf(" ");
        for (int k = 1; k <= 2 * (rows - r) + 1; k++)   /* stars */
            printf("*");
        printf("\n");
    }
    return 0;
}

Build and Run

$ gcc -Wall -std=c11 -o ep_inv_pyramid ep_inv_pyramid.c
$ ./ep_inv_pyramid
*********
 *******
  *****
   ***
    *

Line-by-Line Walkthrough

  • Outer loop – r runs from 1 to rows; each pass prints one line.
  • Blank loop – s < r prints exactly r - 1 blanks, so row 1 has none.
  • Star loop – the upper limit 2 * (rows - r) + 1 gives 9, 7, 5, 3, 1.
  • Newline – placed after both inner loops, never inside them.
Declaration inside for: writing for (int r = 1; ...) needs C99 or newer. Compile with -std=c11 (or a recent GCC default) and you are safe. Older embedded toolchains configured for C89 require declaring the variables at the top of the block.

Star Diamond Pattern in C with One Loop

A diamond is an upright pyramid stacked on an inverted pyramid that shares its widest row. A beginner approach uses two separate outer loops. A neater approach uses one outer loop of 2n - 1 rows and computes the width index for each row:

w = (r <= n) ? r : 2 * n - r;

For n = 4, rows 1 to 7 produce widths 1, 2, 3, 4, 3, 2, 1 – exactly the rise-and-fall we want. Once you have w, blanks are n - w and stars are 2w - 1.

Width index across a diamond (n = 4)
Rows 1-4w = r1, 2, 3, 4
Rows 5-7w = 2n – r3, 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(" ");
        for (int k = 0; k < 2 * w - 1; k++)
            printf("*");
        printf("\n");
    }
    return 0;
}
$ gcc -Wall -std=c11 -o ep_diamond ep_diamond.c
$ ./ep_diamond
   *
  ***
 *****
*******
 *****
  ***
   *

Changing the Size

Because n is the only input, you can change the diamond size by editing one number. In a real project, read it with scanf or accept it as a function argument. Wrapping the logic in void print_diamond(int n) makes the code reusable inside any larger firmware module.

Pattern Programs in Embedded C Programming

Why does a free embedded C course spend time on stars? Because the skills transfer directly:

Pattern skillReal embedded use
Row/column loopsRefreshing an 8×8 LED matrix or a small OLED buffer
Leading blanksRight-aligning or centring text on a 16×2 character LCD
Formula per rowComputing bar-graph lengths for a battery or signal indicator
Loop bounds from a variableSizing UART log tables based on a configuration value

Common Mistakes with Star Pyramid Patterns in C

  • Newline in the wrong place. Putting printf("\n") inside a star loop prints one star per line.
  • Off-by-one on blanks. Using s <= r instead of s < r shifts the whole pyramid by one column.
  • Forgetting the shared middle row. A diamond built from two full pyramids of n rows prints the widest row twice.
  • Reusing one counter. Reusing k in the outer and inner loops creates an endless loop or truncated output.
  • Tabs instead of blanks. A \t is not one column; use plain blanks for geometry.

Best Practices and Performance Notes

  • Write the row table on paper first, then code the formulas.
  • Use putchar(' ') and putchar('*') for single characters; they avoid format-string parsing and suit tiny targets.
  • Test with n = 1 and n = 2; edge sizes expose bound errors immediately.
  • Keep size in a named variable or #define, never a magic number buried in a loop.
  • On a microcontroller, printing over a slow UART blocks the CPU, so avoid heavy output inside time-critical code.

Practice Challenges

  1. Print an upright pyramid using the formulas from the table.
  2. Print a hollow diamond that shows only the outline stars.
  3. Replace the star with the row number (1, 2, 3, …) and observe the shape.
  4. Write print_diamond(int n) and call it for n = 2, 3 and 6.

Summary and Key Takeaways

  • Outer loop = rows; inner loops = blanks and symbols; newline closes the row.
  • Inverted pyramid: blanks r - 1, stars 2(n - r) + 1.
  • Diamond: use a width index w that rises to n and falls back.
  • Formulas first, code second – this habit scales to real firmware.

You now know how star pyramid patterns in C are built from first principles. This is exactly the type of exercise that turns loop syntax into loop intuition, and it is the foundation for the numeric diamonds in the next lecture of this free C tutorial.

Frequently Asked Questions

What is the easiest way to print a star pyramid in C?

Use one outer loop for rows and two inner loops, one for leading blanks and one for stars, then print a newline.

Why are my pyramid stars not aligned?

Usually the blank count is off by one or a tab character was used. Use exact blank counts derived from a row table.

Can I print a diamond with only one outer loop?

Yes. Loop 2n – 1 rows and compute the width index with a conditional expression.

Do pattern programs help with embedded C programming?

They train row and column indexing, which you reuse for LED matrices, LCD text and display buffers.

Is this part of a free C programming course?

Yes, EmbeddedPathashala offers this free embedded C course with tutorials, quizzes and interview questions.

Which C standard do I need?

C99 or newer for declarations inside the for statement; otherwise declare counters at the top of the block.

Keep Learning with the Free Embedded C Course

Continue the free C programming course and move on to number diamonds, then build up to embedded C programming on real microcontrollers.

PREV_LEC | NEXT_LEC

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

1 Comment

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 →