Perfect Square Spiral 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 in C++ by filling a 2D grid from the outside in, using boundary variables to control each spiral ring.

You’ll also learn how to print the result in a clean grid using setw from <iomanip>.

⭐ Pattern Output

For a 10×10 spiral, the output looks like this:

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

Complete C++ Program (10×10)

This version follows the same approach as the reference: fill the grid ring-by-ring using low and high boundaries, then print with setw(4).

C++
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int a[10][10], i, j, low = 0, high = 9, n = 1;

    for (i = 0; i < 5; i++, low++, high--) {
        for (j = low; j <= high; j++, n++)
            a[i][j] = n;
        for (j = low + 1; j <= high; j++, n++)
            a[j][high] = n;
        for (j = high - 1; j >= low; j--, n++)
            a[high][j] = n;
        for (j = high - 1; j > low; j--, n++)
            a[j][low] = n;
    }

    cout << "\t\tPerfect Square Spiral\n";
    for (i = 0; i < 10; i++) {
        cout << "\n";
        for (j = 0; j < 10; j++)
            cout << setw(4) << a[i][j];
        cout << "\n";
    }

    return 0;
}

🧠 How It Works

1

Track the ring boundaries

low and high mark the current square ring we are filling. After each ring, we do low++ and high-- to move inward.

Boundaries
2

Fill 4 sides per ring

Each ring is filled in four passes: top row, right column, bottom row, then left column. The counter n increases after each cell assignment.

Ring fill
3

Repeat until the center

For a 10×10 grid, there are 5 rings (outer loop runs 5 times). In general, rings are about n/2.

Inward
4

Print with fixed width

setw(4) aligns values into columns so the spiral is easy to read.

Formatting
=

Spiral grid

Every cell is written exactly once, so time complexity is O(n²).

2

Variation — User Input Size (n×n Spiral)

This version works for any size \(n\) (within a reasonable limit) by using a dynamic 2D grid.

C++
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main() {
    int n;
    cout << "Enter size n (3..25): ";
    cin >> n;

    if (n < 3 || n > 25) return 0;

    vector<vector<int>> a(n, vector<int>(n, 0));
    int low = 0, high = n - 1;
    int val = 1;

    while (low <= high) {
        for (int j = low; j <= high; j++) a[low][j] = val++;
        for (int i = low + 1; i <= high; i++) a[i][high] = val++;
        for (int j = high - 1; j >= low; j--) a[high][j] = val++;
        for (int i = high - 1; i > low; i--) a[i][low] = val++;
        low++;
        high--;
    }

    cout << "\nPerfect Square Spiral\n";
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) cout << setw(4) << a[i][j];
        cout << "\n";
    }

    return 0;
}

💡 Tips for Enhancement

Try These

  • Increase the width in setw for large n so columns stay aligned
  • Try starting the spiral from the center and expanding outward
  • Print the spiral using characters or custom labels instead of numbers
  • Store the grid and reuse it for additional operations (sum of diagonals, etc.)
  • Convert it into a function buildSpiral(n) for reuse

Avoid

  • Forgetting to move boundaries inward (will cause overwrites)
  • Using an output width that is too small (columns will shift)
  • Using very large n without considering console readability
  • Mixing indices (rows vs columns) when filling edges

Key Takeaways

1

Use boundaries to fill each spiral ring from outside to inside.

2

Fill four edges per ring: top, right, bottom, and left.

3

Printing with setw keeps the grid readable.

4

Time complexity is O(n²) since all cells are filled once.

❓ Frequently Asked Questions

Yes. The boundary approach works for both. For odd n, the last ring is a single center cell; for even n, the last ring is a 2×2 block.
Each loop fills one edge: top row, right column, bottom row, and left column. Doing it in order produces a clean spiral without gaps.
Yes. Change the order of edge-filling (or swap directions in the loops) to spiral clockwise vs counterclockwise.
O(n²), because the algorithm writes each of the \(n^2\) cells once.

Explore More C++ Pattern Programs!

Matrix patterns like spirals are a fun way to practice indices and boundaries.

All Number Patterns →
Did you know?

Spiral filling is a common interview pattern. The same boundary technique is used for printing matrices in spiral order and for rotating matrix layers.

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