C Square Number Pyramid Pattern

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A square-number pyramid prints perfect squares from a running counter m in centered odd-width rows: 1 square, then 3, then 5, and so on.

Remember
Rule: m = 1; maxWidth = 2*levels - 1
      for i = 1, 3, 5, ... maxWidth
        indent (maxWidth - i) groups of "  "
        print m*m with %4d, i times; m++

                   1
               4   9  16
          25  36  49  64  81
     100 121 144 169 196 225 256
 289 324 361 400 441 484 529 576 625   ← 5 levels

Follows the alternating 1/0 pattern in Program 40; next is Program 42.

How to Solve It

Start with fixed 5 levels (i <= 9), then generalize with scanf — optionally drop the indent loop for a left-aligned trace.

MethodIdeaBest for
Centered pyramidOdd i, indent spaces, print %4d of m*mLearning, interviews, exams
Left-alignedSame squares; skip the indent loopPaper tracing of m

Pseudocode

Pseudocode
m = 1
maxWidth = 2 * levels - 1
for i from 1 to maxWidth step 2:
    for j from i to maxWidth - 1:
        print two spaces
    for k from 1 to i:
        print m*m in width 4; m++
    print newline

Cheat sheet

GoalPattern
Odd row widthsfor (i = 1; i <= maxWidth; i += 2)
Center the rowfor (j = i; j < maxWidth; j++) printf(" ");
Print next squareprintf("%4d", m * m); m++;
End the rowprintf("\n");
Levels → widthmaxWidth = 2 * levels - 1

Printing Numbers vs Starting a New Line

APIEffectUse for
printf(" ") / printf("%4d", m * m)Stays on the same lineIndent groups and each square
printf("\n")Ends the current lineAfter indent + print loops

Print spaces and squares without a newline, then end the row once.

Live Preview

Change the level count and the centered square pyramid updates instantly — each square uses a width-4 field like %4d.

Whole numbers from 1 to 5 so every square still fits in %4d. Tap a chip or type a value — the preview redraws as you go.

Live result 5 levels · 25 squares
                   1
               4   9  16
          25  36  49  64  81
     100 121 144 169 196 225 256
 289 324 361 400 441 484 529 576 625

Worked Walkthrough — levels = 3

With maxWidth = 5, trace each odd i, indent groups, and the m values used for m*m.

iIndent groupsm usedSquaresPrinted row
14111
322, 3, 44, 9, 164 9 16
505..925..8125 36 49 64 81

Total squares for n levels = 1 + 3 + … + (2n - 1) = n² (here 9). That square sum is why time is O(n²).

C Programs

Three complete programs: fixed 5 levels, scanf levels, and a left-aligned variant. Use View Output to reveal sample results.

Example 1 — Fixed 5 Levels

Hard-coded pyramid — i <= 9, indent with " ", print %4d of m*m.

C
#include <stdio.h>

int main(void)
{
    int i, j, k;
    int m = 1;

    for (i = 1; i <= 9; i += 2)
    {
        for (j = i; j < 9; j++)
            printf("  ");

        for (k = 1; k <= i; k++)
        {
            printf("%4d", m * m);
            m++;
        }

        printf("\n");
    }

    return 0;
}

How It Works

1. Odd widths. i steps 1, 3, 5, 7, 9 — that is how many squares print on each row.

2. Indent then print. The j loop prints two spaces per remaining gap; the k loop prints m*m with %4d and bumps m.

3. End the line. printf("\n") runs only after both inner loops finish.

When i = 1 you get 1; when i = 3 you get 4, 9, 16.

Example 2 — User Input Levels

Read levels with scanf, set maxWidth = 2 * levels - 1, and reject invalid input.

C
#include <stdio.h>

int main(void)
{
    int levels;
    int i, j, k;
    int m = 1;
    int maxWidth;

    printf("Enter number of levels: ");
    if (scanf("%d", &levels) != 1 || levels < 1)
        return 0;

    maxWidth = 2 * levels - 1;

    for (i = 1; i <= maxWidth; i += 2)
    {
        for (j = i; j < maxWidth; j++)
            printf("  ");

        for (k = 1; k <= i; k++)
        {
            printf("%4d", m * m);
            m++;
        }

        printf("\n");
    }

    return 0;
}

How It Works

1. Prompt and validate. Exit early if scanf fails or levels < 1.

2. Derive width. maxWidth = 2 * levels - 1 replaces the hard-coded 9 in both loops.

3. Safer input tip. Prefer an explicit message instead of a silent exit:

Safer input
if (scanf("%d", &levels) != 1 || levels < 1 || levels > 5)
{
    printf("Enter a whole number from 1 to 5.\n");
    return 1;
}

Example 3 — Left-Aligned Pyramid

Same squares and counter — no leading spaces, easier to trace m on paper.

C
#include <stdio.h>

int main(void)
{
    int i, k;
    int m = 1;

    for (i = 1; i <= 9; i += 2)
    {
        for (k = 1; k <= i; k++)
        {
            printf("%4d", m * m);
            m++;
        }
        printf("\n");
    }

    return 0;
}

How It Works

1. Same squares. Odd i, m*m, and %4d stay identical to Example 1.

2. Drop the indent. Removing the j loop leaves rows flush left — useful while learning the counter.

3. Add centering next. Once the sequence is clear, restore the indent loop for the full pyramid.

Edge Cases & Pitfalls

Check these before calling the solution done.

no m++

Repeated squares

Forgetting m++ prints the same square every column. Increment after each printed value.

i++

Even row widths

If the outer loop steps by 1, you get even counts and break the classic pyramid. Keep i += 2.

indent mismatch

Off-center pyramid

The indent bound must match the outer maximum (9 or maxWidth). A smaller bound leaves rows skewed.

\n inside

Broken rows

If printf("\n") sits inside the print loop, each square lands on its own line. Call the newline only after the row finishes.

%4d overflow

Wide squares

Squares at 1000+ need a wider field. Cap demos at 5 levels, or switch to %5d / long for larger pyramids.

scanf

Check the return value

If scanf fails, levels may be uninitialized — always test scanf(...) == 1.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(levels²)O(1)
Left-aligned (Example 3)O(levels²)O(1)

Total squares = n² because odd numbers sum to a square. For 5 levels that is 25 printed values (plus indent work also proportional to n²).

Key Takeaways

  • Rule: odd i, indent spaces, print %4d of m*m, then m++.
  • Continuous squares: never reset m between rows — the sequence keeps climbing.
  • Match bounds: indent loop and outer loop share the same maxWidth.
  • Complexity: O(n²) time from n² squares; O(1) extra space.

One line: for odd i, indent, print i squares of m*m with %4d and m++, then printf("\n").

Frequently Asked Questions

A centered pyramid of perfect squares: row 1 prints 1 (1²), row 2 prints 4 9 16 (2², 3², 4²), and so on.
The outer loop increases i by 2 each time (i += 2), so i takes odd values — each becomes the count of squares printed on that row.
An indentation loop prints two spaces before each row while j runs from i to maxWidth-1. As i grows, fewer spaces print, so wider rows stay centered.
m starts at 1 and increments after every printed square. Each value printed is m*m — the next perfect square in sequence.
Fixed-width columns keep the pyramid aligned as squares grow from 1 to 625. Without it, columns drift apart.
Increase the outer-loop maximum (e.g. i <= 11) and match the indent bound — or use levels input as in Example 2.
Program 40 alternates 1 and 0 with shrinking rows. Program 41 prints perfect squares in a centered pyramid with growing odd-width rows.
O(n²) for n levels — total prints are 1+3+5+...+(2n-1) = n².

Did you know?

Each printed value is m² from a running counter m. Row widths are odd (1, 3, 5, 7, 9) — total prints for n levels = n².

Next: Hollow Square Border of 1s

Continue with a 5×5 grid that prints 1s only on the border cells.

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