Pattern Programs in C: Pyramid, Diamond, Floyd’s and Pascal’s Triangles

Tested C code for 16 star, number and letter patterns, the formula behind each row, a cell-rule method for any shape, and the same patterns in Java.

A pyramid, a diamond and a hollow diamond made of square cells, the shapes printed by pattern programs in C

Every star pattern in C comes down to one formula per row. In a pyramid of n rows, row i has n − i spaces and then 2i − 1 stars. Change those two numbers and the same pair of nested loops prints a right triangle, an inverted pyramid, a diamond or an hourglass. Work the formula out first and write the loops second, and most pattern programs are correct on the first run.

This guide starts with a complete pyramid program for beginners, then gives the row formula for 16 patterns: squares, triangles, pyramids, diamonds, hollow shapes, number patterns, Floyd’s triangle, Pascal’s triangle and an alphabet triangle. It also shows a second technique that draws a shape from a rule instead of counting stars, a real-life bar chart built the same way, the five mistakes that break pattern programs most often, and the same patterns in Java. Every program was compiled and tested with GCC and Clang on Ubuntu and with MSVC on Windows, and every output block on this page is the program’s real output.

How to Print a Pyramid Pattern 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 leading spaces and one that prints the stars. For n rows, row i (counting from 1) gets n − i spaces and 2i − 1 stars, followed by a newline. Here is the complete program. It asks for the number of rows and checks the answer before it draws anything:

/* pyramid: asks for a number of rows and prints a centered pyramid of stars.
   Row i (counting from 1) has n - i spaces and then 2i - 1 stars. */
#include <stdio.h>

int main(void)
{
    int n;
    printf("Number of rows (1-50): ");
    if (scanf("%d", &n) != 1 || n < 1 || n > 50) {
        printf("\nPlease enter a whole number from 1 to 50.\n");
        return 1;
    }
    putchar('\n');
    for (int i = 1; i <= n; i++) {
        for (int s = 0; s < n - i; s++)          /* leading spaces */
            putchar(' ');
        for (int k = 0; k < 2 * i - 1; k++)      /* stars: 1, 3, 5, ... */
            putchar('*');
        putchar('\n');
    }
    return 0;
}

Output (typing 5 at the prompt):

Number of rows (1-50): 5

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

The outer for loop runs once per row. The first inner loop prints n - i spaces, so the first row is pushed furthest to the right and the last row not at all. The second inner loop prints 2 * i - 1 stars: 1, 3, 5, 7, 9. Because every row has an odd number of stars, each row has a middle star, and the middle stars line up in one column. If loops are new to you, the for and while loops in C tutorial explains how they run.

The if before the drawing matters too. scanf returns the number of values it read, so scanf("%d", &n) != 1 catches input such as five, and the range check stops a request for a million rows. Mistake 4 below shows what happens without it.

The Row Formula for Pyramids and Diamonds

The easiest way to get a pattern right is to write a table before writing code: one line per row, with the number of spaces and stars in that row. For the 5-row pyramid above:

Row iSpaces (n − i)Stars (2i − 1)Width of the row
1415
2336
3257
4178
5099

Look down each column and the formula is visible: the spaces fall by one per row and the stars rise by two. The same method gives every pattern in this guide:

PatternRowsSpaces in row iStars in row i
Right triangle (half pyramid)n0i
Inverted right trianglen0n − i + 1
Mirrored right trianglenn − ii
Pyramidnn − i2i − 1
Inverted pyramidni − 12(n − i) + 1
Diamond2n − 1pyramid rows 1 to n, then rows n − 1 down to 1as the pyramid row
Hourglass2n − 1pyramid rows n down to 1, then rows 2 to nas the pyramid row
The row formula: n − i spaces, then 2i − 1 stars Grey outlines are spaces, blue cells are stars. Each row stops after its last star. PYRAMID, n = 5 row 1: 4 spaces, 1 star row 2: 3 spaces, 3 stars row 3: 2 spaces, 5 stars row 4: 1 space, 7 stars row 5: 0 spaces, 9 stars DIAMOND, n = 4 rows 1 to n rows n − 1 to 1 The widest row belongs to the top half only, so the diamond has 2n − 1 = 7 rows.
Figure 1: The row formula behind pyramid and diamond patterns in C. Row i of an n-row pyramid has n − i spaces and 2i − 1 stars; a diamond adds rows n − 1 down to 1 underneath. Both shapes are drawn from the output of the article’s patterns program.

A diamond is a pyramid with an inverted pyramid under it, and an hourglass is the same two halves in the other order. Both have 2n − 1 rows, not 2n, because the widest row (or the narrowest, for the hourglass) is shared by the two halves and printed once.

Star Patterns in C

The patterns below come from one small library in the companion repository. Each pattern is a function that takes the number of rows and writes to a FILE *, so the same code prints to the screen in the demo program and to a file in the tests. All of them use one helper that prints a character a given number of times:

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

The demo program prints any pattern by name: patterns NAME ROWS. The outputs below come from it.

Square and hollow square

A square is n rows of n stars. A hollow square prints a star only on the border: in the first row, the last row, the first column or the last column. Every other cell is a space.

static void hollow_square(FILE *out, int n)
{
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++)
            fputc(i == 1 || i == n || j == 1 || j == n ? '*' : ' ', out);
        fputc('\n', out);
    }
}

Output of patterns hollow-square 5:

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

Right triangle, inverted and mirrored

A right triangle, also called a half pyramid, prints i stars in row i and no spaces. Counting i down from n turns it upside down. Adding n − i spaces in front of each row aligns it to the right:

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 hollow pyramid

Because so many patterns are built from pyramid rows, the library has one function that prints a single row, and the pyramid and inverted pyramid only choose the order of the rows:

/* One row of a centered pyramid of height n: n - i spaces, 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 hollow pyramid keeps the same spaces but prints a star only at the first and last position of each row, and fills the whole bottom row so that the shape is closed:

static void hollow_pyramid(FILE *out, int n)
{
    for (int i = 1; i <= n; i++) {
        repeat(out, ' ', n - i);
        for (int k = 1; k <= 2 * i - 1; k++)
            fputc(k == 1 || k == 2 * i - 1 || i == n ? '*' : ' ', out);
        fputc('\n', out);
    }
}

Output of patterns hollow-pyramid 5:

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

How to print a diamond pattern in C

To print a diamond, print a pyramid of n rows and then the same rows from n − 1 down to 1. Starting the lower half at n − 1 is the important detail: it keeps the widest row from appearing twice.

/* A diamond is a pyramid of n rows on top of an inverted pyramid of n - 1:
   the widest row is printed once, 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 hollow diamond uses the hollow-row rule from the hollow pyramid without the filled bottom row, and an hourglass swaps the two 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:

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

Number and Letter Patterns in C

Number patterns use the same loops with a number in place of the star. The two simplest differ in one variable: printing the column number j gives 1, 1 2, 1 2 3, and printing the row number i gives 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, because from row 10 the numbers have two digits and the columns no longer line up. Floyd’s triangle solves that problem properly.

Floyd’s triangle in C

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

/* Floyd's triangle: consecutive numbers, row i holds i of them. Every
   column is as wide as the largest number, so the columns line up. */
static void floyd(FILE *out, int n)
{
    int width = digits((long long)n * (n + 1) / 2), next = 1;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++)
            fprintf(out, j == 1 ? "%*d" : " %*d", width, next++);
        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 field width from the argument list, so the width can be computed at run time (see fprintf in POSIX). The helper digits() counts the digits of a number by dividing by 10 until one digit is left.

Pascal’s triangle in C

In Pascal’s triangle, each number is the sum of the two numbers above it, and entry k of row r is the binomial coefficient C(r, k), the number of ways to choose k items from r. The library computes each entry directly with the multiplicative formula C(r, j) = C(r, j − 1) × (r − j + 1) / j, arranged so that it never overflows while the result still fits:

unsigned long long pascal_entry(int r, int k)
{
    if (k < 0 || k > r)
        return 0;
    if (k > r - k)
        k = r - k;                       /* C(r, k) = C(r, r - k) */
    unsigned long long c = 1;
    for (int j = 1; j <= k; j++) {
        /* c = c * m / j, where the division is exact. Dividing first keeps
           the intermediate value no larger than the result: with g =
           gcd(m, j), j / g has no factor in common with m / g, so it must
           divide c. */
        unsigned long long m = (unsigned long long)(r - k + j), g = gcd(m, (unsigned long long)j);
        unsigned long long q = c / ((unsigned long long)j / g), f = m / g;
        if (q > UINT64_MAX / f)
            return 0;                    /* the entry does not fit in 64 bits */
        c = q * f;
    }
    return c;
}

Dividing before multiplying is what keeps the numbers small, and the greatest common divisor makes that division exact. Computed this way, every entry up to row 67 fits in an unsigned 64-bit integer, and the function returns 0 instead of a wrong number when an entry does not. Printing the triangle is then a matter of spacing. Every entry is right-aligned in a cell of the same even width, and each row is indented by half a cell more than the row below it, so each number sits between the two numbers it came from:

/* Pascal's triangle, centered. Every entry is printed right-aligned in a
   cell of the same even width w, and row r is indented by (n - 1 - r)
   half-cells, so each entry sits between the two entries above it. */
static void pascal(FILE *out, int n)
{
    int w = digits((long long)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 k = 0; k <= r; k++)
            fprintf(out, "%*llu", k == 0 ? w / 2 : w, pascal_entry(r, k));
        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 follow the same rule with characters. Row i prints the first i letters of the alphabet, so the pattern 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

Another Way to Print Patterns: Test Every Cell

Counting spaces and stars works well for triangles. For shapes such as an X, a plus sign or a circle, a second method is easier: go through every cell of a square grid and ask whether that cell belongs to the shape. Measure x and y from the center of the grid, and each shape becomes a one-line rule:

ShapeRule for the cell (x, y), with the size r
Diamond|x| + |y| ≤ r
Hollow diamond|x| + |y| = r
X|x| = |y|
Plusx = 0 or y = 0
Circlex² + y² ≤ r² + r
Triangle (pyramid)y ≤ 0 and |x| ≤ y + r
/* shapes: a second way to draw patterns. Instead of counting spaces and
   stars per row, test every cell of a grid: the shape is a rule that
   says whether cell (x, y) is filled. x and y are measured from the
   center, so symmetric shapes have short rules.

   usage: shapes NAME SIZE     NAME: diamond, hollow-diamond, x, plus, circle, triangle */
#include <stdio.h>
#include <stdlib.h>
#include <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)           { (void)r; return x == 0 || y == 0; }
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 both directions. A row stops at its
   rightmost filled cell, so no line ends in spaces; rows with no filled
   cell are not printed at all. */
static void draw(rule filled, int r)
{
    for (int y = -r; y <= r; y++) {
        int last = -r - 1;
        for (int x = -r; x <= r; x++)
            if (filled(x, y, r))
                last = x;
        if (last < -r)
            continue;
        for (int x = -r; x <= last; x++)
            putchar(filled(x, y, r) ? '*' : ' ');
        putchar('\n');
    }
}

int main(int argc, char **argv)
{
    static const struct { const char *name; 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].name) == 0 && r >= 1 && r <= 30) {
            draw(shapes[i].f, r);
            return 0;
        }
    fprintf(stderr, "usage: 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 draws exactly the same diamond as the row-by-row version: shapes diamond 3 and patterns diamond 4 have identical expected output files in the tests. The circle rule uses r² + r rather than r², which rounds the edge outward by half a cell and gives a rounder shape on a coarse grid. Characters in a terminal are about twice as tall as they are wide, so the circle looks taller than it is wide on screen.

Drawing a shape with one rule per cell Each cell shows the value of the rule at (x, y), measured from the center. 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 same loop prints an X (|x| = |y|), a plus (x = 0 or y = 0) or a triangle.
Figure 2: The cell-rule method. The shapes program tests every cell of a grid against a rule such as |x| + |y| ≤ r and prints a star where the rule holds. The filled cells match the program’s real output for a diamond and a circle of size 3.

The cell method costs more work, one test per cell instead of one loop per row, but for a terminal pattern that is a few hundred tests. It is also the idea behind real graphics: a program that fills a shape on screen asks the same question for every pixel.

Real-Life Example: A Bar Chart in the Terminal

Pattern programs are not only exercises. Command-line tools draw charts, progress bars and histograms with exactly the same loops. This program reads monthly download counts from a text file and draws a vertical bar chart, row by row from the top: a column gets ### in a row if its bar reaches that row.

The data file:

# month downloads
Jan 1200
Feb 1850
Mar 2400
Apr 2100
May 3150
Jun 2900
/* barchart: draws a vertical bar chart from "label value" lines, the way a
   command-line report or a log summary might. It is a pattern program in
   disguise: row by row from the top, a column gets a '#' if its bar is at
   least that tall.

   usage: barchart FILE [HEIGHT]     (HEIGHT defaults to 8 rows) */
#include <stdio.h>
#include <stdlib.h>

#define MAX_BARS 24

int main(int argc, char **argv)
{
    if (argc < 2 || argc > 3) {
        fprintf(stderr, "usage: barchart FILE [HEIGHT]\n");
        return 2;
    }
    int height = argc == 3 ? atoi(argv[2]) : 8;
    if (height < 1 || height > 40) {
        fprintf(stderr, "barchart: HEIGHT must be from 1 to 40\n");
        return 2;
    }
    FILE *in = fopen(argv[1], "r");
    if (in == NULL) {
        fprintf(stderr, "barchart: cannot open %s\n", argv[1]);
        return 2;
    }
    char label[MAX_BARS][4], line[128];
    long value[MAX_BARS], max = 0;
    int n = 0;
    while (n < MAX_BARS && fgets(line, sizeof line, in) != NULL)
        if (line[0] != '#' && sscanf(line, "%3s %ld", label[n], &value[n]) == 2 && value[n] >= 0) {
            if (value[n] > max)
                max = value[n];
            n++;
        }
    fclose(in);
    if (n == 0 || max == 0) {
        fprintf(stderr, "barchart: no values to draw\n");
        return 2;
    }

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

    for (int row = height; row >= 1; row--) {
        int last = -1;
        for (int i = 0; i < n; i++)
            if (bar[i] >= row)
                last = i;                  /* stop after the last bar on this row */
        printf("%6ld |", max * row / height);
        for (int i = 0; i <= last; i++)
            printf(" %s", bar[i] >= row ? "###" : "   ");
        putchar('\n');
    }
    printf("%6s +", "");
    for (int i = 0; i < n; i++)
        printf("----");
    printf("\n%6s  ", "");
    for (int i = 0; i < n; i++)
        printf(" %-3s", label[i]);
    putchar('\n');
    return 0;
}

Output of barchart data/downloads.txt:

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

Two details make the chart honest. Each bar is scaled to the chart height with rounding, (value * height + max / 2) / max, rather than truncation, which would make every bar look up to one row shorter than it is. And each row stops after its last bar, so the program prints no trailing spaces, the same rule the pattern library follows. The same approach draws a histogram of response times or a [##### ] progress bar.

Common Mistakes in Pattern Programs

Each mistake below is a small program in the repository’s pitfalls directory, and the output is that program’s real output.

1. One star too many: <= instead of <

The star loop of a pyramid must run 2i − 1 times. Writing k <= 2 * i instead of k < 2 * i prints 2i stars, an even number, so no row has a middle star and the pyramid leans:

Output:

k < 2 * i  (correct)
   *
  ***
 *****
*******

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

Check the first two rows of any pattern by hand against the formula table. Off-by-one errors show up there immediately.

2. Printing the middle row of a diamond twice

If the lower half of a diamond starts at row n instead of n − 1, the widest row is printed twice and the diamond gets a flat middle and 2n rows:

Output:

lower half from n - 1 (correct)
   *
  ***
 *****
*******
 *****
  ***
   *

lower half from n (middle row twice)
   *
  ***
 *****
*******
*******
 *****
  ***
   *

3. Trailing spaces at the end of each line

On screen these two pyramids look the same. The second one pads every row to the full width, so each line ends in spaces. Here | shows where each line really ends:

Output:

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

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

Online judges, automated graders and tests that compare output byte for byte reject the padded version, and so does diff. Stop each row after its last star.

4. Not checking what scanf read

scanf("%d", &n) returns 0 when the input is not a number. It reads nothing and leaves n unchanged, so a program that ignores the return value carries on with whatever n already held. Given the input four, this program prints a 5-row pyramid without any error, because n was initialized to 5:

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

Output:

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

If n had not been initialized at all, reading it would be undefined behavior. The pyramid program at the top of this page checks the return value and the range, and rejects four:

Output (typing four at the prompt):

Number of rows (1-50): four

Please enter a whole number from 1 to 50.

5. Computing Pascal’s triangle with factorials

The textbook formula C(r, k) = r! / (k! (r − k)!) looks like the obvious way to compute an entry. It fails much earlier than the entries do: 21! is larger than the biggest 64-bit unsigned integer, so from row 21 the factorials wrap around silently and the division produces nonsense. The biggest entry of row 21 is only 352,716:

Output:

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

The multiplicative formula avoids the factorials, but the order of operations still matters. Multiplying before dividing, c * m / j, even with an overflow check before the multiplication, has to give up at row 63 (entry 29), because the intermediate product no longer fits. Dividing first, as pascal_entry() does, works up to row 67.

Pattern Programs in Java

The same patterns in Java use the same formula. Java 11 added String.repeat(), which replaces the inner loops: " ".repeat(n - i) is the row’s spaces and "*".repeat(2 * i - 1) its stars. Here is the pyramid program, with the same prompt and the same input check as the C version:

import java.util.Scanner;

/**
 * Asks for a number of rows and prints a centered pyramid of stars.
 * Row i (counting from 1) has n - i spaces and then 2i - 1 stars.
 */
public final class Pyramid {
    private Pyramid() {
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Number of rows (1-50): ");
        if (!in.hasNextInt()) {
            System.out.print("\nPlease enter a whole number from 1 to 50.\n");
            System.exit(1);
        }
        int n = in.nextInt();
        if (n < 1 || n > 50) {
            System.out.print("\nPlease enter a whole number 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))          // leading spaces
               .append("*".repeat(2 * i - 1))      // stars: 1, 3, 5, ...
               .append('\n');
        }
        System.out.print(out);
    }
}

Output (typing 5 at the prompt):

Number of rows (1-50): 5

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

The Java library builds each pattern as a String. A diamond is again a pyramid of n rows followed by rows n − 1 down to 1:

/** Row i of a centered pyramid of height n: n - i spaces, 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 once. */
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 details keep the Java output identical to the C output. Lines end with "\n", not %n or println(), which write "\r\n" on Windows. And Java’s long is signed, so Pascal’s entries fit only up to row 66 instead of 67; pascalEntry() uses Math.multiplyExact(), which throws on overflow, and returns −1 instead of a wrong value. Java’s tests compare all 16 patterns with the C program’s expected output files, so the two versions cannot drift apart. To draw star shapes in a window rather than in the console, see the Java program to draw star shapes with Swing.

How the Code Is Tested

A pattern that looks right at 5 rows can be wrong at 37. Instead of comparing a few outputs, the C tests check rules that describe each shape, for every allowed size:

  • Shape rules at every size. For each of the 16 patterns and every size from 1 to its limit, the tests check the number of rows, the spaces and stars in each row, the symmetry of diamonds and hourglasses, the borders of hollow shapes and the numbers in the number patterns. No line may end in a space. That is 98,667 checks.
  • Pascal’s triangle against the addition rule. Every entry up to row 67 is compared with the sum of the two entries above it, and the middle entry of row 68, which does not fit in 64 bits, must be reported as 0.
  • Exact output. The demo, the shapes, the bar chart, the pyramid program (with valid and invalid input) and the five pitfall programs must print exactly what is shown on this page. Java’s tests compare against the same expected files.
  • Deliberate mistakes. tests/mutations.py puts ten plausible bugs into the library one at a time and checks that the tests fail for each:
Deliberate mistakeCheck that failed
pyramid rows get 2i starsis_pyramid_row(lines[i - 1], n, i)
pyramid indent one shortis_pyramid_row(lines[i - 1], n, i)
diamond repeats its middle rowrows == 2 * n - 1
hollow pyramid base left openstars == 2 * n - 1
hollow square misses the bottom edgecount_char(lines[r], '*') == (edge ? n : 2)
hourglass repeats its waistrows == 2 * n - 1
Floyd’s triangle restarts every rowv == expect++
Pascal entries: multiply before dividingpascal_entry(r, k) == row[k]
Pascal entries ignore symmetry wronglypascal_entry(r, k) == row[k]
number triangle repeats the row numberstrcmp(lines[i - 1], want) == 0

Key Takeaways

  • Write the row table before the code. For a pyramid of n rows, row i has n − i spaces and 2i − 1 stars; every other pattern here is a variation of that table.
  • A diamond is a pyramid plus an inverted pyramid of n − 1 rows, so it has 2n − 1 rows and its widest row appears once.
  • Hollow patterns print a star only on the edges: the first and last position of a row, plus the closing row where the shape needs one.
  • Shapes such as X, plus and circle are easier as a rule for each cell (x, y), measured from the center.
  • Never end a line with spaces, and always check scanf‘s return value and the range before drawing.
  • Compute Pascal’s triangle without factorials. Use the multiplicative formula and divide before multiplying; factorials overflow 64 bits at row 21.
  • The same loops draw real output: bar charts, histograms and progress bars in command-line tools.

Conclusion

Pattern programs are a beginner exercise because they make nested loops visible: every mistake in a loop’s start, end or step shows up as a crooked line of stars. The habit that solves them, writing down what each row must contain before writing the loop that prints it, is the same habit that makes any loop correct.

From here, two directions are worth trying. Make the patterns take their size and shape from the command line, as the demo program does, or move from characters to pixels with the cell-rule method, which is how simple graphics fill shapes. For more C programming, see the C programming section.

Source Code and Tests

C patterns workflow status
Java patterns workflow status

All C programs on this page are in the loops/patterns directory of the MYCPLUS C examples repository, and the Java versions are in loops/patterns in the Java examples repository.

Build, test and run the C version:

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

The Java version needs Java 17 or later:

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

What the build checks.

  • Compilers: GCC and Clang under C11 and C17 with -Wall -Wextra -pedantic -Werror on Linux, and MSVC under /W4 /WX on Windows. Java is compiled with -Xlint:all -Werror and tested on Java 17, 21 and 25, on Linux and Windows.
  • Output: every program prints exactly what is shown on this page, from the same expected files on every system and in both languages.
  • Sanitizers and mutations: the tests run clean under AddressSanitizer and UndefinedBehaviorSanitizer, and all ten deliberate mistakes are caught.

What I Verified

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

CheckUbuntu 24.04Windows 11
C builds with warnings as errors: GCC and Clang (C11 and C17) on Ubuntu, MSVC /W4 /WX (C11 and C17) on WindowsPassedMSVC /W4 /WX, C11 and C17: built
CTest: shape rules, Pascal entries and byte-for-byte outputs37 of 37 in all four configurations37 of 37 in C11 and in C17
Shape-rule checks for all 16 patterns at every allowed size98,667 passedPassed (in the CTest unit tests, C11 and C17)
AddressSanitizer and UndefinedBehaviorSanitizer, every test37 of 37, cleanNot applicable
Valgrind memcheck: unit tests, barchart, pyramidNo errors, no leaksNot applicable
Code cross-compiled with MinGW-w64, warnings as errorsPassedNot applicable
10 deliberate mistakes injected into the library10 of 10 caughtNot run
Java: compiled with -Xlint:all -Werror, output identical to the C expected files, shape rules, Pascal up to row 66OpenJDK 21: 24,988 checks passedJava 27: all six checks passed, including the 24,988-check test

Not covered: macOS, 32-bit builds, compilers older than GCC 13 or Clang 18, and Java versions other than 21 and 27 outside CI.

Scroll to Top