Perfect Square Spiral Pattern in C#

Beginner
⏱️ 9 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
2D Array + Boundaries

What You’ll Learn

How to generate a perfect square spiral (also called a spiral matrix) in C# using a 2D array.

You’ll fill the grid layer-by-layer using low and high boundaries and print the result with fixed-width formatting.

⭐ Pattern Output

For a 10×10 grid, the pattern looks like this:

Output
1    2    3    4    5    6    7    8    9   10\n36  37   38   39   40   41   42   43   44   11\n35  64   65   66   67   68   69   70   45   12\n34  63   84   85   86   87   88   71   46   13\n33  62   83   96   97   98   89   72   47   14\n32  61   82   95  100   99   90   73   48   15\n31  60   81   94   93   92   91   74   49   16\n30  59   80   79   78   77   76   75   50   17\n29  58   57   56   55   54   53   52   51   18\n28  27   26   25   24   23   22   21   20   19
1

Complete C# Program

Fill a 10×10 array by walking the boundaries in a spiral: top row, right column, bottom row, left column—then move inward.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] arr = new int[10, 10];
            int i, j, low = 0, high = 9, n = 1;

            for (i = 0; i < 5; i++, low++, high--)
            {
                for (j = low; j <= high; j++, n++)
                    arr[i, j] = n;

                for (j = low + 1; j <= high; j++, n++)
                    arr[j, high] = n;

                for (j = high - 1; j >= low; j--, n++)
                    arr[high, j] = n;

                for (j = high - 1; j > low; j--, n++)
                    arr[j, low] = n;
            }

            Console.WriteLine("Perfect Square Spiral");
            for (i = 0; i < 10; i++)
            {
                Console.WriteLine();
                for (j = 0; j < 10; j++)
                    Console.Write("{0, 4}", arr[i, j]);
                Console.WriteLine();
            }
        }
    }
}

🧠 How It Works

1

Create a 2D array

int[,] arr = new int[10,10]; holds the spiral values.

Setup
2

Track the current layer boundaries

low and high mark the current square ring. After each ring, low++ and high--.

Boundaries
3

Fill 4 sides per layer

Each layer is filled in this order: top row, right column, bottom row, left column, incrementing n each time.

Spiral
4

Print with fixed width

Console.Write("{0, 4}", arr[i,j]) keeps columns aligned.

Formatting
=

Perfect square spiral

The grid has \(n^2\) cells, so filling and printing takes O(n²) time.

2

Variation — User Input Size

Generate an \(n \times n\) spiral for any positive n. This version uses four boundaries (top, bottom, left, right) and fills while shrinking them.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter size n: ");
            if (!int.TryParse(Console.ReadLine(), out int n) || n <= 0)
            {
                Console.WriteLine("Please enter a positive integer.");
                return;
            }

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

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

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

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

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

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                    Console.Write("{0, 4}", a[i, j]);
                Console.WriteLine();
            }
        }
    }
}

💡 Tips for Enhancement

Try These

  • Use a larger print width if \(n^2\) can exceed 9999
  • Reverse the spiral direction by changing the fill order
  • Start from the center instead of the border for a different style
  • Store the output as a string table for easier alignment control

Avoid

  • Printing without fixed width (columns won’t align for 2+ digits)
  • Forgetting boundary checks (you may overwrite values or go out of bounds)
  • Using an \(n\) so large that the console output becomes unreadable

Key Takeaways

1

A spiral matrix is generated by filling one border layer at a time.

2

Boundaries (top/bottom/left/right) make spiral logic easier to manage.

3

Fixed-width formatting keeps large grids readable.

4

Time complexity is O(n²) for an \(n \times n\) spiral.

❓ Frequently Asked Questions

Yes. This is a classic spiral matrix generation exercise: fill the grid while shrinking boundaries.
Yes. The boundary-based approach works for any positive size \(n\), both odd and even.
A 10×10 grid has 5 concentric rings (each ring reduces both width and height by 2).
O(n²), because every cell in the grid is filled and printed once.

Explore More C# Pattern Programs!

Spiral matrices are a great bridge from simple loops to 2D array reasoning.

All Number Patterns →
Did you know?

Spiral-matrix logic shows up in many places: image processing, grid simulations, and interview tasks that require careful boundary control.

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