C Perfect Square Spiral Pattern

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

What Is This Pattern?

A perfect square spiral (spiral matrix) fills an n×n grid with consecutive numbers 1..n² walking clockwise around shrinking border layers.

Remember
Rule: top → right → bottom → left, then shrink boundaries

   1   2   3   4
  12  13  14   5
  11  16  15   6
  10   9   8   7     ← n = 4

Follows the growing reverse pattern in Program 61; next explore C star patterns.

How to Solve It

Allocate a 2D array. Maintain top, bottom, left, right. Fill four sides per layer, then move those walls inward until they cross.

MethodIdeaBest for
Four-boundary spiralFill top/right/bottom/left, then shrinkLearning, interviews, exams
Fixed-width printprintf("%4d", value)Aligned columns for multi-digit values

Pseudocode

Pseudocode
top = 0, bottom = n - 1, left = 0, right = n - 1
val = 1
while top <= bottom and left <= right:
    fill top row left→right; top = top + 1
    fill right column top→bottom; right = right - 1
    if top <= bottom:
        fill bottom row right→left; bottom = bottom - 1
    if left <= right:
        fill left column bottom→top; left = left + 1
print the grid

Cheat sheet

GoalPattern
Boundariestop = 0; bottom = n - 1; left = 0; right = n - 1;
Top sidefor (j = left; j <= right; j++) a[top][j] = val++;
Right sidefor (i = top; i <= bottom; i++) a[i][right] = val++;
Bottom / leftSame idea reversed; guard with if (top <= bottom) / if (left <= right)
Print cellprintf("%4d", a[i][j]);

Printing Numbers vs Starting a New Line

APIEffectUse for
printf("%4d", a[i][j])Stays on the same lineEach cell in a row
printf("\n")Ends the current lineAfter every row of n cells

Print cells without a newline, then end the row once.

Live Preview

Change the grid size and the clockwise spiral updates instantly — capped at 8 so the matrix stays readable.

Whole numbers from 1 to 8. Tap a chip or type a value — the preview redraws as you go.

Live result n = 4 · 16 cells
   1   2   3   4
  12  13  14   5
  11  16  15   6
  10   9   8   7

Worked Walkthrough — Outer Layer for n = 4

Trace the first ring so the four-side order and boundary shrink are clear.

SideActionValues filled
Topa[0][0..3], then top++1 2 3 4
Righta[1..3][3], then right--5 6 7
Bottoma[3][2..0], then bottom--8 9 10
Lefta[2..1][0], then left++11 12

Inner 2×2 then fills 13 14 / 16 15. Total cells = n² → O(n²).

C Programs

Three complete programs: fixed 10×10, scanf size, and a compact 4×4 demo. Use View Output to reveal sample results.

Example 1 — Fixed 10×10 Spiral

Hard-coded size — fill with four boundaries, print with width 4 (numbers 1–100).

C
#include <stdio.h>

int main(void)
{
    int n = 10;
    int a[10][10];
    int i, j;
    int top = 0, bottom = n - 1, left = 0, right = n - 1;
    int val = 1;

    while (top <= bottom && left <= right)
    {
        for (j = left; j <= right; j++)
            a[top][j] = val++;
        top++;

        for (i = top; i <= bottom; i++)
            a[i][right] = val++;
        right--;

        if (top <= bottom)
        {
            for (j = right; j >= left; j--)
                a[bottom][j] = val++;
            bottom--;
        }

        if (left <= right)
        {
            for (i = bottom; i >= top; i--)
                a[i][left] = val++;
            left++;
        }
    }

    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
            printf("%4d", a[i][j]);
        printf("\n");
    }

    return 0;
}

How It Works

1. Outer layer first. Top fills 1..10, right continues downward, then bottom and left close the ring.

2. Shrink inward. After each side, move that boundary so the next layer starts one cell inside.

3. Align. %4d keeps 1–100 lined up in neat columns.

Example 2 — User Input Size

Read n with scanf, allocate a VLA, then run the same spiral fill.

C
#include <stdio.h>

int main(void)
{
    int n;
    int i, j;

    printf("Enter size n: ");
    if (scanf("%d", &n) != 1 || n <= 0)
    {
        printf("Please enter a positive integer.\n");
        return 1;
    }

    int a[n][n];
    int top = 0, bottom = n - 1, left = 0, right = n - 1;
    int val = 1;

    while (top <= bottom && left <= right)
    {
        for (j = left; j <= right; j++)
            a[top][j] = val++;
        top++;

        for (i = top; i <= bottom; i++)
            a[i][right] = val++;
        right--;

        if (top <= bottom)
        {
            for (j = right; j >= left; j--)
                a[bottom][j] = val++;
            bottom--;
        }

        if (left <= right)
        {
            for (i = bottom; i >= top; i--)
                a[i][left] = val++;
            left++;
        }
    }

    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
            printf("%4d", a[i][j]);
        printf("\n");
    }

    return 0;
}

How It Works

1. Prompt and validate. Require n > 0 before declaring the VLA.

2. Same core. Boundary fill matches Example 1 — only n comes from the user.

3. Safer input tip. Cap demos for readable console output:

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

Example 3 — Compact 4×4 Trace

Sixteen cells — easy to dry-run every side of the outer and inner layers on paper.

C
#include <stdio.h>

int main(void)
{
    int n = 4;
    int a[4][4];
    int i, j;
    int top = 0, bottom = n - 1, left = 0, right = n - 1;
    int val = 1;

    while (top <= bottom && left <= right)
    {
        for (j = left; j <= right; j++)
            a[top][j] = val++;
        top++;

        for (i = top; i <= bottom; i++)
            a[i][right] = val++;
        right--;

        if (top <= bottom)
        {
            for (j = right; j >= left; j--)
                a[bottom][j] = val++;
            bottom--;
        }

        if (left <= right)
        {
            for (i = bottom; i >= top; i--)
                a[i][left] = val++;
            left++;
        }
    }

    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
            printf("%4d", a[i][j]);
        printf("\n");
    }

    return 0;
}

How It Works

1. Two layers. Outer ring uses 1–12; inner 2×2 uses 13–16.

2. Guards matter. The if (top <= bottom) / if (left <= right) checks prevent double-filling when only one row or column remains.

3. Scale up next. Once the small demo is clear, use Examples 1–2 for 10×10 or user input.

Edge Cases & Pitfalls

Check these before calling the solution done.

no guards

Double-filled middle

On odd n, skipping the if (top <= bottom) / if (left <= right) checks can overwrite the center cell.

%d only

Crooked columns

Without %4d, single-digit and three-digit numbers misalign. Keep a fixed field width.

\n inside

Broken rows

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

n = 1

Single cell

Output is just 1 — a good sanity check for the while condition.

wrong side order

Not a spiral

Keep the clockwise order top → right → bottom → left. Swapping sides breaks the ring.

scanf

Check before the VLA

Validate scanf before int a[n][n] — a failed read leaves n uninitialized.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(n²)O(n²) array
Compact 4×4 (Example 3)O(n²)O(n²) array

Every cell is written once and printed once → O(n²) time. The 2D array uses O(n²) space.

Key Takeaways

  • Four sides per layer: top → right → bottom → left, then shrink.
  • Guard odd centers: check top <= bottom and left <= right before the reverse sides.
  • Align with width 4: printf("%4d", ...) keeps multi-digit columns neat.
  • Complexity: O(n²) time and O(n²) array space for an n×n fill.

One line: walk each ring clockwise with shrinking top/bottom/left/right until 1..n² is filled.

Frequently Asked Questions

It prints a perfect square spiral (spiral matrix) filled with numbers 1..n² in a clockwise spiral — e.g. 10×10 holds 1–100.
Those four variables mark the current layer. After filling a side, you move that boundary inward and continue.
Using printf("%4d", value) prints each number in a fixed width of 4 characters, keeping columns aligned.
Program 61 uses a while loop on one number. Program 62 fills an n×n grid with a 2D array and boundary-based spiral loops.
Yes. This is a classic spiral matrix generation exercise: fill the grid while shrinking boundaries.
Yes. The boundary approach works for any positive n, both odd and even.
A 1×1 grid holds only the value 1 — one cell, one layer.
O(n²) for an n×n grid because each cell is filled and printed once.

Did you know?

A perfect square spiral fills an n×n grid with numbers 1..n² by walking each border layer clockwise and tightening boundaries — runtime is O(n²).

Next: C Star Patterns

Continue with star-pattern tutorials after finishing the number series.

Star patterns →

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