New: 77 pattern programs with tested code in C, C++, Java and Python Explore patterns

Spiral Number Matrix (Clockwise)

Read summary with AI tools
Table of contents
  1. Spiral Number Matrix output
  2. How the spiral number matrix works
  3. Spiral Number Matrix in C
  4. Spiral Number Matrix in C++
  5. Spiral Number Matrix in Java
  6. Spiral Number Matrix in Python
  7. Time and space complexity
  8. Related patterns

The numbers 1 to n² are written into an n × n matrix in a clockwise spiral, starting at the top-left corner. This tutorial shows the output, a row-by-row diagram and the complete program in C, C++, Java and Python.

This program is part of the Spiral Patterns collection.

Spiral Number Matrix output

Output (n = 4):

  1  2  3  4
 12 13 14  5
 11 16 15  6
 10  9  8  7
Spiral Number Matrix layout diagram, row by row (n = 4)
The numbers of the spiral number matrix laid out row by row (n = 4).

How the spiral number matrix works

Keep four boundaries: top, bottom, left and right. Fill the top row left to right, the right column top to bottom, the bottom row right to left and the left column bottom to top, shrinking the matching boundary after each side. Stop when the boundaries cross, then print the matrix.

Spiral Number Matrix in C

#include <stdio.h>

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

    while (top <= bottom && left <= right) {
        for (int j = left; j <= right; j++)
            a[top][j] = value++;
        top++;
        for (int i = top; i <= bottom; i++)
            a[i][right] = value++;
        right--;
        if (top <= bottom) {
            for (int j = right; j >= left; j--)
                a[bottom][j] = value++;
            bottom--;
        }
        if (left <= right) {
            for (int i = bottom; i >= top; i--)
                a[i][left] = value++;
            left++;
        }
    }

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

Spiral Number Matrix in C++

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

int main() {
    int n = 4;
    vector<vector<int>> a(n, vector<int>(n));
    int top = 0, bottom = n - 1, left = 0, right = n - 1;
    int value = 1;

    while (top <= bottom && left <= right) {
        for (int j = left; j <= right; j++)
            a[top][j] = value++;
        top++;
        for (int i = top; i <= bottom; i++)
            a[i][right] = value++;
        right--;
        if (top <= bottom) {
            for (int j = right; j >= left; j--)
                a[bottom][j] = value++;
            bottom--;
        }
        if (left <= right) {
            for (int i = bottom; i >= top; i--)
                a[i][left] = value++;
            left++;
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            cout << setw(3) << a[i][j];
        cout << endl;
    }
    return 0;
}

Spiral Number Matrix in Java

public class SpiralNumberMatrix {
    public static void main(String[] args) {
        int n = 4;
        int[][] a = new int[n][n];
        int top = 0, bottom = n - 1, left = 0, right = n - 1;
        int value = 1;

        while (top <= bottom && left <= right) {
            for (int j = left; j <= right; j++)
                a[top][j] = value++;
            top++;
            for (int i = top; i <= bottom; i++)
                a[i][right] = value++;
            right--;
            if (top <= bottom) {
                for (int j = right; j >= left; j--)
                    a[bottom][j] = value++;
                bottom--;
            }
            if (left <= right) {
                for (int i = bottom; i >= top; i--)
                    a[i][left] = value++;
                left++;
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                System.out.printf("%3d", a[i][j]);
            System.out.println();
        }
    }
}

Spiral Number Matrix in Python

n = 4
a = [[0] * n for _ in range(n)]
top, bottom, left, right = 0, n - 1, 0, n - 1
value = 1

while top <= bottom and left <= right:
    for j in range(left, right + 1):
        a[top][j] = value
        value += 1
    top += 1
    for i in range(top, bottom + 1):
        a[i][right] = value
        value += 1
    right -= 1
    if top <= bottom:
        for j in range(right, left - 1, -1):
            a[bottom][j] = value
            value += 1
        bottom -= 1
    if left <= right:
        for i in range(bottom, top - 1, -1):
            a[i][left] = value
            value += 1
        left += 1

for i in range(n):
    for j in range(n):
        print(f"{a[i][j]:3d}", end="")
    print()

Time and space complexity

Every cell is filled once and printed once, so the program runs in O(n²) time. It stores the whole n × n matrix, so it uses O(n²) memory.

Authored by

Ghanendra Yadav runs Pattern Programs from Bangalore, India. The site started in 2020 to help students practise loops and logic through pattern programs in C, C++, Java and Python. Every program published here is compiled and run before it goes live, and the output shown is the real output.

Latest articles

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.