Sunday, November 22, 2026
HomeC ProgrammingPyramid, Diamond and Star Patterns

Pyramid, Diamond and Star Patterns


Each star sample in C comes down to at least one components per row. In a pyramid of n rows, row i has n − i areas after which 2i − 1 stars. Change these two numbers and the identical pair of nested loops prints a proper triangle, an inverted pyramid, a diamond or an hourglass. Work the components out first and write the loops second, and most sample packages are appropriate on the primary run.

This information begins with an entire pyramid program for learners, then provides the row components for 16 patterns: squares, triangles, pyramids, diamonds, hole shapes, quantity patterns, Floyd’s triangle, Pascal’s triangle and an alphabet triangle. It additionally reveals a second approach that attracts a form from a rule as an alternative of counting stars, a real-life bar chart constructed the identical means, the 5 errors that break sample packages most frequently, and the identical patterns in Java. Each program was compiled and examined with GCC and Clang on Ubuntu and with MSVC on Home windows, and each output block on this web page is this system’s actual output.

Learn how to Print a Pyramid Sample in C

To print a pyramid in C, use two nested loops: an outer loop for the rows, and inside it one loop that prints the main areas and one which prints the celebs. For n rows, row i (counting from 1) will get n − i areas and 2i − 1 stars, adopted by a newline. Right here is the entire program. It asks for the variety of rows and checks the reply earlier than it attracts something:

/* pyramid: asks for quite a lot of rows and prints a centered pyramid of stars.
   Row i (counting from 1) has n - i areas after which 2i - 1 stars. */
#embody <stdio.h>

int essential(void)
{
    int n;
    printf("Variety of rows (1-50): ");
    if (scanf("%d", &n) != 1 || n < 1 || n > 50) {
        printf("nPlease enter an entire quantity from 1 to 50.n");
        return 1;
    }
    putchar('n');
    for (int i = 1; i <= n; i++) {
        for (int s = 0; s < n - i; s++)          /* main areas */
            putchar(' ');
        for (int ok = 0; ok < 2 * i - 1; ok++)      /* stars: 1, 3, 5, ... */
            putchar('*');
        putchar('n');
    }
    return 0;
}

Output (typing 5 on the immediate):

Variety of rows (1-50): 5

    *
   ***
  *****
 *******
*********

The outer for loop runs as soon as per row. The primary interior loop prints n - i areas, so the primary row is pushed furthest to the best and the final row by no means. The second interior loop prints 2 * i - 1 stars: 1, 3, 5, 7, 9. As a result of each row has an odd variety of stars, every row has a center star, and the center stars line up in a single column. If loops are new to you, the for and whereas loops in C tutorial explains how they run.

The if earlier than the drawing issues too. scanf returns the variety of values it learn, so scanf("%d", &n) != 1 catches enter corresponding to 5, and the vary examine stops a request for 1,000,000 rows. Mistake 4 beneath reveals what occurs with out it.

The Row Formulation for Pyramids and Diamonds

The simplest method to get a sample proper is to write down a desk earlier than writing code: one line per row, with the variety of areas and stars in that row. For the 5-row pyramid above:

Row i Areas (n − i) Stars (2i − 1) Width of the row
1 4 1 5
2 3 3 6
3 2 5 7
4 1 7 8
5 0 9 9

Look down every column and the components is seen: the areas fall by one per row and the celebs rise by two. The identical technique provides each sample on this information:

Sample Rows Areas in row i Stars in row i
Proper triangle (half pyramid) n 0 i
Inverted proper triangle n 0 n − i + 1
Mirrored proper triangle n n − i i
Pyramid n n − i 2i − 1
Inverted pyramid n i − 1 2(n − i) + 1
Diamond 2n − 1 pyramid rows 1 to n, then rows n − 1 right down to 1 because the pyramid row
Hourglass 2n − 1 pyramid rows n right down to 1, then rows 2 to n because the pyramid row
The row components: n − i areas, then 2i − 1 stars Gray outlines are areas, blue cells are stars. Every row stops after its final star. PYRAMID, n = 5 row 1: 4 areas, 1 star row 2: 3 areas, 3 stars row 3: 2 areas, 5 stars row 4: 1 house, 7 stars row 5: 0 areas, 9 stars DIAMOND, n = 4 rows 1 to n rows n − 1 to 1 The widest row belongs to the highest half solely, so the diamond has 2n − 1 = 7 rows.

Determine 1: The row components behind pyramid and diamond patterns in C. Row i of an n-row pyramid has n − i areas and 2i − 1 stars; a diamond provides rows n − 1 right down to 1 beneath. Each shapes are drawn from the output of the article’s patterns program.

A diamond is a pyramid with an inverted pyramid beneath it, and an hourglass is similar two halves within the different order. Each have 2n − 1 rows, not 2n, as a result of the widest row (or the narrowest, for the hourglass) is shared by the 2 halves and printed as soon as.

Star Patterns in C

The patterns beneath come from one small library within the companion repository. Every sample is a perform that takes the variety of rows and writes to a FILE *, so the identical code prints to the display screen within the demo program and to a file within the assessments. All of them use one helper that prints a personality a given variety of instances:

static void repeat(FILE *out, char c, int rely)
{
    for (int i = 0; i < rely; i++)
        fputc(c, out);
}

The demo program prints any sample by title: patterns NAME ROWS. The outputs beneath come from it.

Sq. and hole sq.

A sq. is n rows of n stars. A hole sq. prints a star solely on the border: within the first row, the final row, the primary column or the final column. Each different cell is an area.

static void hollow_square(FILE *out, int n)
{
    for (int i = 1; i <= n; i++)  j == 1 
}

Output of patterns hollow-square 5:

*****
*   *
*   *
*   *
*****

Proper triangle, inverted and mirrored

A proper triangle, additionally referred to as a half pyramid, prints i stars in row i and no areas. Counting i down from n turns it the wrong way up. Including n − i areas in entrance of every row aligns it to the best:

static void mirrored_right_triangle(FILE *out, int n)   /* right-aligned */
{
    for (int i = 1; i <= n; i++) {
        repeat(out, ' ', n - i);
        repeat(out, '*', i);
        fputc('n', out);
    }
}

Output of patterns right-triangle 4:

*
**
***
****

Output of patterns mirrored-right-triangle 4:

   *
  **
 ***
****

Pyramid, inverted pyramid and hole pyramid

As a result of so many patterns are constructed from pyramid rows, the library has one perform that prints a single row, and the pyramid and inverted pyramid solely select the order of the rows:

/* One row of a centered pyramid of peak n: n - i areas, 2i - 1 stars. */
static void pyramid_row(FILE *out, int n, int i)
{
    repeat(out, ' ', n - i);
    repeat(out, '*', 2 * i - 1);
    fputc('n', out);
}
static void pyramid(FILE *out, int n)
{
    for (int i = 1; i <= n; i++)
        pyramid_row(out, n, i);
}
static void inverted_pyramid(FILE *out, int n)
{
    for (int i = n; i >= 1; i--)
        pyramid_row(out, n, i);
}

Output of patterns inverted-pyramid 4:

*******
 *****
  ***
   *

A hole pyramid retains the identical areas however prints a star solely on the first and final place of every row, and fills the entire backside row in order that the form is closed:

static void hollow_pyramid(FILE *out, int n)
{
    for (int i = 1; i <= n; i++) 
}

Output of patterns hollow-pyramid 5:

    *
   * *
  *   *
 *     *
*********

Learn how to print a diamond sample in C

To print a diamond, print a pyramid of n rows after which the identical rows from n − 1 right down to 1. Beginning the decrease half at n − 1 is the vital element: it retains the widest row from showing twice.

/* A diamond is a pyramid of n rows on prime of an inverted pyramid of n - 1:
   the widest row is printed as soon as, not twice. */
static void diamond(FILE *out, int n)
{
    for (int i = 1; i <= n; i++)
        pyramid_row(out, n, i);
    for (int i = n - 1; i >= 1; i--)
        pyramid_row(out, n, i);
}

Output of patterns diamond 5:

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

A hole diamond makes use of the hollow-row rule from the hole pyramid with out the crammed backside row, and an hourglass swaps the 2 halves of the diamond:

static void hourglass(FILE *out, int n)
{
    for (int i = n; i >= 1; i--)
        pyramid_row(out, n, i);
    for (int i = 2; i <= n; i++)
        pyramid_row(out, n, i);
}

Output of patterns hollow-diamond 4:

   *
  * *
 *   *
*     *
 *   *
  * *
   *

Output of patterns hourglass 4:

*******
 *****
  ***
   *
  ***
 *****
*******

Quantity and Letter Patterns in C

Quantity patterns use the identical loops with a quantity instead of the star. The 2 easiest differ in a single variable: printing the column quantity j provides 1, 1 2, 1 2 3, and printing the row quantity i provides 1, 2 2, 3 3 3.

static void number_triangle(FILE *out, int n)            /* 1, 12, 123 */
{
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++)
            fprintf(out, j == 1 ? "%d" : " %d", j);
        fputc('n', out);
    }
}

Output of patterns number-triangle 4:

1
1 2
1 2 3
1 2 3 4

Output of patterns repeated-number-triangle 4:

1
2 2
3 3 3
4 4 4 4

The library limits these two to 9 rows, as a result of from row 10 the numbers have two digits and the columns now not line up. Floyd’s triangle solves that downside correctly.

Floyd’s triangle in C

Floyd’s triangle, named after the pc scientist Robert Floyd, fills the rows with consecutive numbers: row i holds i of them. One counter carries on from row to row, and each quantity is printed with the width of the most important one, n(n + 1)/2, so the columns line up:

/* Floyd's triangle: consecutive numbers, row i holds i of them. Each
   column is as huge as the most important quantity, so the columns line up. */
static void floyd(FILE *out, int n)
{
    int width = digits((lengthy lengthy)n * (n + 1) / 2), subsequent = 1;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++)
            fprintf(out, j == 1 ? "%*d" : " %*d", width, subsequent++);
        fputc('n', out);
    }
}

Output of patterns floyd 5:

 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15

The * in %*d takes the sphere width from the argument checklist, so the width could be computed at run time (see fprintf in POSIX). The helper digits() counts the digits of a quantity by dividing by 10 till one digit is left.

Pascal’s triangle in C

In Pascal’s triangle, every quantity is the sum of the 2 numbers above it, and entry ok of row r is the binomial coefficient C(r, ok), the variety of methods to decide on ok objects from r. The library computes every entry immediately with the multiplicative components C(r, j) = C(r, j − 1) × (r − j + 1) / j, organized in order that it by no means overflows whereas the consequence nonetheless matches:

unsigned lengthy lengthy pascal_entry(int r, int ok)
{
    if (ok < 0 || ok > r)
        return 0;
    if (ok > r - ok)
        ok = r - ok;                       /* C(r, ok) = C(r, r - ok) */
    unsigned lengthy lengthy c = 1;
    for (int j = 1; j <= ok; j++) {
        /* c = c * m / j, the place the division is actual. Dividing first retains
           the intermediate worth no bigger than the consequence: with g =
           gcd(m, j), j / g has no think about widespread with m / g, so it should
           divide c. */
        unsigned lengthy lengthy m = (unsigned lengthy lengthy)(r - ok + j), g = gcd(m, (unsigned lengthy lengthy)j);
        unsigned lengthy lengthy q = c / ((unsigned lengthy lengthy)j / g), f = m / g;
        if (q > UINT64_MAX / f)
            return 0;                    /* the entry doesn't slot in 64 bits */
        c = q * f;
    }
    return c;
}

Dividing earlier than multiplying is what retains the numbers small, and the best widespread divisor makes that division actual. Computed this manner, each entry as much as row 67 matches in an unsigned 64-bit integer, and the perform returns 0 as an alternative of a fallacious quantity when an entry doesn’t. Printing the triangle is then a matter of spacing. Each entry is right-aligned in a cell of the identical even width, and every row is indented by half a cell greater than the row beneath it, so every quantity sits between the 2 numbers it got here from:

/* Pascal's triangle, centered. Each entry is printed right-aligned in a
   cell of the identical even width w, and row r is indented by (n - 1 - r)
   half-cells, so every entry sits between the 2 entries above it. */
static void pascal(FILE *out, int n)
{
    int w = digits((lengthy lengthy)pascal_entry(n - 1, (n - 1) / 2)) + 1;
    if (w % 2)
        w++;
    for (int r = 0; r < n; r++) {
        repeat(out, ' ', (n - 1 - r) * w / 2);
        for (int ok = 0; ok <= r; ok++)
            fprintf(out, "%*llu", ok == 0 ? w / 2 : w, pascal_entry(r, ok));
        fputc('n', out);
    }
}

Output of patterns pascal 7:

             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1
   1   5  10  10   5   1
 1   6  15  20  15   6   1

Alphabet triangle

Letter patterns observe the identical rule with characters. Row i prints the primary i letters of the alphabet, so the sample stops at 26 rows:

static void alphabet_triangle(FILE *out, int n)          /* A, AB, ABC */
{
    static const char letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (int i = 1; i <= n; i++) {
        fwrite(letters, 1, (size_t)i, out);
        fputc('n', out);
    }
}

Output of patterns alphabet-triangle 5:

A
AB
ABC
ABCD
ABCDE

One other Strategy to Print Patterns: Take a look at Each Cell

Counting areas and stars works effectively for triangles. For shapes corresponding to an X, a plus signal or a circle, a second technique is simpler: undergo each cell of a sq. grid and ask whether or not that cell belongs to the form. Measure x and y from the middle of the grid, and every form turns into a one-line rule:

Form Rule for the cell (x, y), with the dimensions r
Diamond |x| + |y| ≤ r
Hole diamond |x| + |y| = r
X |x| = |y|
Plus x = 0 or y = 0
Circle x² + y² ≤ r² + r
Triangle (pyramid) y ≤ 0 and |x| ≤ y + r
/* shapes: a second means to attract patterns. As a substitute of counting areas and
   stars per row, take a look at each cell of a grid: the form is a rule that
   says whether or not cell (x, y) is crammed. x and y are measured from the
   middle, so symmetric shapes have brief guidelines.

   utilization: shapes NAME SIZE     NAME: diamond, hollow-diamond, x, plus, circle, triangle */
#embody <stdio.h>
#embody <stdlib.h>
#embody <string.h>

typedef int (*rule)(int x, int y, int r);

static int diamond(int x, int y, int r)        { return abs(x) + abs(y) <= r; }
static int hollow_diamond(int x, int y, int r) { return abs(x) + abs(y) == r; }
static int cross_x(int x, int y, int r)        { (void)r; return abs(x) == abs(y); }
static int plus(int x, int y, int r)           
static int circle(int x, int y, int r)         { return x * x + y * y <= r * r + r; }
static int triangle(int x, int y, int r)       { return y <= 0 && abs(x) <= y + r; }

/* Prints the cells from -r to r in each instructions. A row stops at its
   rightmost crammed cell, so no line ends in areas; rows with no crammed
   cell are usually not printed in any respect. */
static void draw(rule crammed, int r)
{
    for (int y = -r; y <= r; y++) {
        int final = -r - 1;
        for (int x = -r; x <= r; x++)
            if (crammed(x, y, r))
                final = x;
        if (final < -r)
            proceed;
        for (int x = -r; x <= final; x++)
            putchar(crammed(x, y, r) ? '*' : ' ');
        putchar('n');
    }
}

int essential(int argc, char **argv)
{
    static const struct { const char *title; rule f; } shapes[] = {
        {"diamond", diamond}, {"hollow-diamond", hollow_diamond}, {"x", cross_x},
        {"plus", plus}, {"circle", circle}, {"triangle", triangle},
    };
    int r = argc == 3 ? atoi(argv[2]) : 0;
    for (size_t i = 0; argc == 3 && i < sizeof shapes / sizeof shapes[0]; i++)
        if (strcmp(argv[1], shapes[i].title) == 0 && r >= 1 && r <= 30) {
            draw(shapes[i].f, r);
            return 0;
        }
    fprintf(stderr, "utilization: shapes diamond|hollow-diamond|x|plus|circle|triangle SIZE (1-30)n");
    return 2;
}

Output of shapes diamond 3:

   *
  ***
 *****
*******
 *****
  ***
   *

Output of shapes x 3:

*     *
 *   *
  * *
   *
  * *
 *   *
*     *

Output of shapes circle 3:

  ***
 *****
*******
*******
*******
 *****
  ***

The diamond rule attracts precisely the identical diamond because the row-by-row model: shapes diamond 3 and patterns diamond 4 have an identical anticipated output recordsdata within the assessments. The circle rule makes use of r² + r somewhat than r², which rounds the sting outward by half a cell and provides a rounder form on a rough grid. Characters in a terminal are about twice as tall as they’re huge, so the circle appears taller than it’s huge on display screen.

Drawing a form with one rule per cell Every cell reveals the worth of the rule at (x, y), measured from the middle. Blue cells are printed as stars. Diamond: |x| + |y| ≤ 3 −3 −2 −1 0 1 2 3 x −3 6 5 4 3 4 5 6 −2 5 4 3 2 3 4 5 −1 4 3 2 1 2 3 4 0 3 2 1 0 1 2 3 1 4 3 2 1 2 3 4 2 5 4 3 2 3 4 5 3 6 5 4 3 4 5 6 y Circle: x² + y² ≤ 3² + 3 = 12 −3 −2 −1 0 1 2 3 x −3 18 13 10 9 10 13 18 −2 13 8 5 4 5 8 13 −1 10 5 2 1 2 5 10 0 9 4 1 0 1 4 9 1 10 5 2 1 2 5 10 2 13 8 5 4 5 8 13 3 18 13 10 9 10 13 18 y Change the rule and the identical loop prints an X (|x| = |y|), a plus (x = 0 or y = 0) or a triangle.

Determine 2: The cell-rule technique. The shapes program assessments each cell of a grid in opposition to a rule corresponding to |x| + |y| ≤ r and prints a star the place the rule holds. The crammed cells match this system’s actual output for a diamond and a circle of dimension 3.

The cell technique prices extra work, one take a look at per cell as an alternative of 1 loop per row, however for a terminal sample that could be a few hundred assessments. It is usually the thought behind actual graphics: a program that fills a form on display screen asks the identical query for each pixel.

Actual-Life Instance: A Bar Chart within the Terminal

Sample packages are usually not solely workout routines. Command-line instruments draw charts, progress bars and histograms with precisely the identical loops. This program reads month-to-month obtain counts from a textual content file and attracts a vertical bar chart, row by row from the highest: a column will get ### in a row if its bar reaches that row.

The information file:

# month downloads
Jan 1200
Feb 1850
Mar 2400
Apr 2100
Could 3150
Jun 2900
/* barchart: attracts a vertical bar chart from "label worth" strains, the way in which a
   command-line report or a log abstract may. It's a sample program in
   disguise: row by row from the highest, a column will get a '#' if its bar is at
   least that tall.

   utilization: barchart FILE [HEIGHT]     (HEIGHT defaults to eight rows) */
#embody <stdio.h>
#embody <stdlib.h>

#outline MAX_BARS 24

int essential(int argc, char **argv)
{
    if (argc < 2 || argc > 3) {
        fprintf(stderr, "utilization: barchart FILE [HEIGHT]n");
        return 2;
    }
    int peak = argc == 3 ? atoi(argv[2]) : 8;
    if (peak < 1 || peak > 40) {
        fprintf(stderr, "barchart: HEIGHT should be from 1 to 40n");
        return 2;
    }
    FILE *in = fopen(argv[1], "r");
    if (in == NULL) {
        fprintf(stderr, "barchart: can't open %sn", argv[1]);
        return 2;
    }
    char label[MAX_BARS][4], line[128];
    lengthy worth[MAX_BARS], max = 0;
    int n = 0;
    whereas (n < MAX_BARS && fgets(line, sizeof line, in) != NULL)
        if (line[0] != '#' && sscanf(line, "%3s %ld", label[n], &worth[n]) == 2 && worth[n] >= 0) {
            if (worth[n] > max)
                max = worth[n];
            n++;
        }
    fclose(in);
    if (n == 0 || max == 0) {
        fprintf(stderr, "barchart: no values to drawn");
        return 2;
    }

    int bar[MAX_BARS];
    for (int i = 0; i < n; i++)            /* scale to 0..peak, rounding to nearest */
        bar[i] = (int)((worth[i] * peak + max / 2) / max);

    for (int row = peak; row >= 1; row--) ", max * row / peak);
        for (int i = 0; i <= final; i++)
            printf(" %s", bar[i] >= row ? "###" : "   ");
        putchar('n');
    
    printf("%6s +", "");
    for (int i = 0; i < n; i++)
        printf("----");
    printf("npercent6s  ", "");
    for (int i = 0; i < n; i++)
        printf(" %-3s", label[i]);
    putchar('n');
    return 0;
}

Output of barchart information/downloads.txt:

  3150 |                 ###
  2756 |                 ### ###
  2362 |         ###     ### ###
  1968 |     ### ### ### ### ###
  1575 |     ### ### ### ### ###
  1181 | ### ### ### ### ### ###
   787 | ### ### ### ### ### ###
   393 | ### ### ### ### ### ###
       +------------------------
         Jan Feb Mar Apr Could Jun

Two particulars make the chart sincere. Every bar is scaled to the chart peak with rounding, (worth * peak + max / 2) / max, somewhat than truncation, which might make each bar look as much as one row shorter than it’s. And every row stops after its final bar, so this system prints no trailing areas, the identical rule the sample library follows. The identical strategy attracts a histogram of response instances or a [##### ] progress bar.

Frequent Errors in Sample Applications

Every mistake beneath is a small program within the repository’s pitfalls listing, and the output is that program’s actual output.

1. One star too many: <= as an alternative of <

The star loop of a pyramid should run 2i − 1 instances. Writing ok <= 2 * i as an alternative of ok < 2 * i prints 2i stars, a good quantity, so no row has a center star and the pyramid leans:

Output:

ok < 2 * i  (appropriate)
   *
  ***
 *****
*******

ok <= 2 * i (one star too many)
   **
  ****
 ******
********

Examine the primary two rows of any sample by hand in opposition to the components desk. Off-by-one errors present up there instantly.

2. Printing the center row of a diamond twice

If the decrease half of a diamond begins at row n as an alternative of n − 1, the widest row is printed twice and the diamond will get a flat center and 2n rows:

Output:

decrease half from n - 1 (appropriate)
   *
  ***
 *****
*******
 *****
  ***
   *

decrease half from n (center row twice)
   *
  ***
 *****
*******
*******
 *****
  ***
   *

3. Trailing areas on the finish of every line

On display screen these two pyramids look the identical. The second pads each row to the total width, so every line ends in areas. Right here | reveals the place every line actually ends:

Output:

stars, then newline (appropriate)
   *|
  ***|
 *****|
*******|

padded to 2n - 1 columns
   *   |
  ***  |
 ***** |
*******|

On-line judges, automated graders and assessments that evaluate output byte for byte reject the padded model, and so does diff. Cease every row after its final star.

4. Not checking what scanf learn

scanf("%d", &n) returns 0 when the enter is just not a quantity. It reads nothing and leaves n unchanged, so a program that ignores the return worth carries on with no matter n already held. Given the enter 4, this program prints a 5-row pyramid with none error, as a result of n was initialized to five:

int essential(void)
{
    int n = 5;                              /* a "default" left from earlier code */
    int obtained = scanf("%d", &n);
    printf("scanf returned %d, n is %dn", obtained, n);
    for (int i = 1; i <= n; i++) {
        for (int ok = 1; ok <= n - i; ok++)
            putchar(' ');
        for (int ok = 1; ok < 2 * i; ok++)
            putchar('*');
        putchar('n');
    }
    return 0;
}

Output:

scanf returned 0, n is 5
    *
   ***
  *****
 *******
*********

If n had not been initialized in any respect, studying it might be undefined conduct. The pyramid program on the prime of this web page checks the return worth and the vary, and rejects 4:

Output (typing 4 on the immediate):

Variety of rows (1-50): 4

Please enter an entire quantity from 1 to 50.

5. Computing Pascal’s triangle with factorials

The textbook components C(r, ok) = r! / (ok! (r − ok)!) appears like the apparent method to compute an entry. It fails a lot sooner than the entries do: 21! is bigger than the most important 64-bit unsigned integer, so from row 21 the factorials wrap round silently and the division produces nonsense. The most important entry of row 21 is barely 352,716:

Output:

row  ok                factorials         multiplicative
20   10                   184756                 184756
21   10                    98014                 352716  <- fallacious
22   11                    10792                 705432  <- fallacious
25   12                        2                5200300  <- fallacious

The multiplicative components avoids the factorials, however the order of operations nonetheless issues. Multiplying earlier than dividing, c * m / j, even with an overflow examine earlier than the multiplication, has to surrender at row 63 (entry 29), as a result of the intermediate product now not matches. Dividing first, as pascal_entry() does, works as much as row 67.

Sample Applications in Java

The identical patterns in Java use the identical components. Java 11 added String.repeat(), which replaces the interior loops: " ".repeat(n - i) is the row’s areas and "*".repeat(2 * i - 1) its stars. Right here is the pyramid program, with the identical immediate and the identical enter examine because the C model:

import java.util.Scanner;

/**
 * Asks for quite a lot of rows and prints a centered pyramid of stars.
 * Row i (counting from 1) has n - i areas after which 2i - 1 stars.
 */
public ultimate class Pyramid {
    personal Pyramid() {
    }

    public static void essential(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Variety of rows (1-50): ");
        if (!in.hasNextInt()) {
            System.out.print("nPlease enter an entire quantity from 1 to 50.n");
            System.exit(1);
        }
        int n = in.nextInt();
        if (n < 1 || n > 50) {
            System.out.print("nPlease enter an entire quantity from 1 to 50.n");
            System.exit(1);
        }
        StringBuilder out = new StringBuilder("n");
        for (int i = 1; i <= n; i++) {
            out.append(" ".repeat(n - i))          // main areas
               .append("*".repeat(2 * i - 1))      // stars: 1, 3, 5, ...
               .append('n');
        }
        System.out.print(out);
    }
}

Output (typing 5 on the immediate):

Variety of rows (1-50): 5

    *
   ***
  *****
 *******
*********

The Java library builds every sample as a String. A diamond is once more a pyramid of n rows adopted by rows n − 1 right down to 1:

/** Row i of a centered pyramid of peak n: n - i areas, then 2i - 1 stars. */
static String pyramidRow(int n, int i) {
    return " ".repeat(n - i) + "*".repeat(2 * i - 1) + "n";
}
/** A pyramid of n rows over an inverted pyramid of n - 1: the widest row as soon as. */
static String diamond(int n) {
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i <= n; i++) {
        sb.append(pyramidRow(n, i));
    }
    for (int i = n - 1; i >= 1; i--) {
        sb.append(pyramidRow(n, i));
    }
    return sb.toString();
}

Output of java PatternsDemo diamond 4:

   *
  ***
 *****
*******
 *****
  ***
   *

Two particulars preserve the Java output an identical to the C output. Traces finish with "n", not %n or println(), which write "rn" on Home windows. And Java’s lengthy is signed, so Pascal’s entries match solely as much as row 66 as an alternative of 67; pascalEntry() makes use of Math.multiplyExact(), which throws on overflow, and returns −1 as an alternative of a fallacious worth. Java’s assessments evaluate all 16 patterns with the C program’s anticipated output recordsdata, so the 2 variations can’t drift aside. To attract star shapes in a window somewhat than within the console, see the Java program to attract star shapes with Swing.

How the Code Is Examined

A sample that appears proper at 5 rows could be fallacious at 37. As a substitute of evaluating just a few outputs, the C assessments examine guidelines that describe every form, for each allowed dimension:

  • Form guidelines at each dimension. For every of the 16 patterns and each dimension from 1 to its restrict, the assessments examine the variety of rows, the areas and stars in every row, the symmetry of diamonds and hourglasses, the borders of hole shapes and the numbers within the quantity patterns. No line might finish in an area. That’s 98,667 checks.
  • Pascal’s triangle in opposition to the addition rule. Each entry as much as row 67 is in contrast with the sum of the 2 entries above it, and the center entry of row 68, which doesn’t slot in 64 bits, should be reported as 0.
  • Actual output. The demo, the shapes, the bar chart, the pyramid program (with legitimate and invalid enter) and the 5 pitfall packages should print precisely what’s proven on this web page. Java’s assessments evaluate in opposition to the identical anticipated recordsdata.
  • Deliberate errors. assessments/mutations.py places ten believable bugs into the library one by one and checks that the assessments fail for every:
Deliberate mistake Examine that failed
pyramid rows get 2i stars is_pyramid_row(strains[i - 1], n, i)
pyramid indent one brief is_pyramid_row(strains[i - 1], n, i)
diamond repeats its center row rows == 2 * n - 1
hole pyramid base left open stars == 2 * n - 1
hole sq. misses the underside edge count_char(strains[r], '*') == (edge ? n : 2)
hourglass repeats its waist rows == 2 * n - 1
Floyd’s triangle restarts each row v == count on++
Pascal entries: multiply earlier than dividing pascal_entry(r, ok) == row[k]
Pascal entries ignore symmetry wrongly pascal_entry(r, ok) == row[k]
quantity triangle repeats the row quantity strcmp(strains[i - 1], need) == 0

Key Takeaways

  • Write the row desk earlier than the code. For a pyramid of n rows, row i has n − i areas and 2i − 1 stars; each different sample here’s a variation of that desk.
  • A diamond is a pyramid plus an inverted pyramid of n − 1 rows, so it has 2n − 1 rows and its widest row seems as soon as.
  • Hole patterns print a star solely on the sides: the primary and final place of a row, plus the closing row the place the form wants one.
  • Shapes corresponding to X, plus and circle are simpler as a rule for every cell (x, y), measured from the middle.
  • By no means finish a line with areas, and at all times examine scanf‘s return worth and the vary earlier than drawing.
  • Compute Pascal’s triangle with out factorials. Use the multiplicative components and divide earlier than multiplying; factorials overflow 64 bits at row 21.
  • The identical loops draw actual output: bar charts, histograms and progress bars in command-line instruments.

Conclusion

Sample packages are a newbie train as a result of they make nested loops seen: each mistake in a loop’s begin, finish or step reveals up as a crooked line of stars. The behavior that solves them, writing down what every row should comprise earlier than writing the loop that prints it, is similar behavior that makes any loop appropriate.

From right here, two instructions are value making an attempt. Make the patterns take their dimension and form from the command line, because the demo program does, or transfer from characters to pixels with the cell-rule technique, which is how easy graphics fill shapes. For extra C programming, see the C programming part.

Supply Code and Checks

C patterns workflow status
Java patterns workflow status

All C packages on this web page are within the loops/patterns listing of the MYCPLUS C examples repository, and the Java variations are in loops/patterns within the Java examples repository.

Construct, take a look at and run the C model:

cmake -S . -B construct
cmake --build construct
ctest --test-dir construct --output-on-failure
./construct/patterns diamond 5

The Java model wants Java 17 or later:

javac --release 17 -d construct src/*.java
java -cp construct PatternsDemo diamond 5

What the construct checks.

  • Compilers: GCC and Clang beneath C11 and C17 with -Wall -Wextra -pedantic -Werror on Linux, and MSVC beneath /W4 /WX on Home windows. Java is compiled with -Xlint:all -Werror and examined on Java 17, 21 and 25, on Linux and Home windows.
  • Output: each program prints precisely what’s proven on this web page, from the identical anticipated recordsdata on each system and in each languages.
  • Sanitizers and mutations: the assessments run clear beneath AddressSanitizer and UndefinedBehaviorSanitizer, and all ten deliberate errors are caught.

What I Verified

The Ubuntu column was run for this text on Ubuntu 24.04 (x86-64, GCC 13.3, Clang 18, CMake 3.28, OpenJDK 21, MinGW-w64 GCC 13, Valgrind). The Home windows column comes from the repositories’ run_all.ps1 scripts on Home windows 11 (MSVC with CMake 4.4, and Java 27).

Examine Ubuntu 24.04 Home windows 11
C builds with warnings as errors: GCC and Clang (C11 and C17) on Ubuntu, MSVC /W4 /WX (C11 and C17) on Home windows Handed MSVC /W4 /WX, C11 and C17: constructed
CTest: form guidelines, Pascal entries and byte-for-byte outputs 37 of 37 in all 4 configurations 37 of 37 in C11 and in C17
Form-rule checks for all 16 patterns at each allowed dimension 98,667 handed Handed (within the CTest unit assessments, C11 and C17)
AddressSanitizer and UndefinedBehaviorSanitizer, each take a look at 37 of 37, clear Not relevant
Valgrind memcheck: unit assessments, barchart, pyramid No errors, no leaks Not relevant
Code cross-compiled with MinGW-w64, warnings as errors Handed Not relevant
10 deliberate errors injected into the library 10 of 10 caught Not run
Java: compiled with -Xlint:all -Werror, output an identical to the C anticipated recordsdata, form guidelines, Pascal as much as row 66 OpenJDK 21: 24,988 checks handed Java 27: all six checks handed, together with the 24,988-check take a look at

Not coated: macOS, 32-bit builds, compilers older than GCC 13 or Clang 18, and Java variations aside from 21 and 27 outdoors CI.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments