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

Print a Matrix in Anticlockwise Spiral Order

Printing a matrix in anticlockwise spiral order means reading it down the first column, along the bottom row, up the last column and back along the top, then repeating on the inner part. For the grid 1 to 16 that gives 1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7.

Quick answer: Keep four boundaries: top, bottom, left and right. Read down the left column, along the bottom, up the right column and back along the top, moving the matching boundary inwards after each side. The two if checks stop a single middle row or column from being read twice.

This program is part of the Spiral Patterns collection.

Table of contents8 sections
  1. Output
  2. How the print a matrix in anticlockwise spiral order works
  3. Program in C
  4. Program in C++
  5. Program in Java
  6. Program in Python
  7. Time and space complexity
  8. Frequently asked questions

Print a Matrix in Anticlockwise Spiral Order output

Output (4 × 4 matrix 1 to 16):

1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7
Print a Matrix in Anticlockwise Spiral Order layout diagram, row by row (4 × 4 matrix 1 to 16)
The numbers of the print a matrix in anticlockwise spiral order laid out row by row (4 × 4 matrix 1 to 16).

How the print a matrix in anticlockwise spiral order works

This is the clockwise spiral order with the four sides taken in the opposite order. After reading a side, that side is used up, so its boundary moves in: left++ after the left column, bottom-- after the bottom row, and so on. The loop stops when the boundaries cross. The extra checks matter for matrices with an odd number of rows or columns, where the last pass is a single line.

  1. Set top = 0, bottom = n − 1, left = 0, right = n − 1.
  2. Read the left column from top to bottom, then increase left.
  3. Read the bottom row from left to right, then decrease bottom.
  4. If columns remain, read the right column upwards and decrease right; if rows remain, read the top row right to left and increase top. Repeat while the boundaries have not crossed.

Key takeaways

  • Four boundaries mark the part of the matrix not read yet.
  • Each side read moves one boundary inwards.
  • The two checks prevent reading a middle row or column twice.
  • Swapping the order of the sides switches between clockwise and anticlockwise.

Print a Matrix in Anticlockwise Spiral Order in C

#include <stdio.h>

int main(void) {
    int n = 4;
    int a[4][4];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            a[i][j] = i * n + j + 1;

    int top = 0, bottom = n - 1, left = 0, right = n - 1;
    while (top <= bottom && left <= right) {
        for (int i = top; i <= bottom; i++)         /* down the left column */
            printf("%d ", a[i][left]);
        left++;
        for (int j = left; j <= right; j++)         /* along the bottom row */
            printf("%d ", a[bottom][j]);
        bottom--;
        if (left <= right) {
            for (int i = bottom; i >= top; i--)     /* up the right column */
                printf("%d ", a[i][right]);
            right--;
        }
        if (top <= bottom) {
            for (int j = right; j >= left; j--)     /* back along the top row */
                printf("%d ", a[top][j]);
            top++;
        }
    }
    printf("\n");
    return 0;
}

Print a Matrix in Anticlockwise Spiral Order in C++

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

int main() {
    int n = 4;
    vector<vector<int>> a(n, vector<int>(n));
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            a[i][j] = i * n + j + 1;

    int top = 0, bottom = n - 1, left = 0, right = n - 1;
    while (top <= bottom && left <= right) {
        for (int i = top; i <= bottom; i++)         // down the left column
            cout << a[i][left] << " ";
        left++;
        for (int j = left; j <= right; j++)         // along the bottom row
            cout << a[bottom][j] << " ";
        bottom--;
        if (left <= right) {
            for (int i = bottom; i >= top; i--)     // up the right column
                cout << a[i][right] << " ";
            right--;
        }
        if (top <= bottom) {
            for (int j = right; j >= left; j--)     // back along the top row
                cout << a[top][j] << " ";
            top++;
        }
    }
    cout << endl;
    return 0;
}

Print a Matrix in Anticlockwise Spiral Order in Java

public class AnticlockwiseSpiralOrder {
    public static void main(String[] args) {
        int n = 4;
        int[][] a = new int[n][n];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                a[i][j] = i * n + j + 1;

        int top = 0, bottom = n - 1, left = 0, right = n - 1;
        while (top <= bottom && left <= right) {
            for (int i = top; i <= bottom; i++)         // down the left column
                System.out.print(a[i][left] + " ");
            left++;
            for (int j = left; j <= right; j++)         // along the bottom row
                System.out.print(a[bottom][j] + " ");
            bottom--;
            if (left <= right) {
                for (int i = bottom; i >= top; i--)     // up the right column
                    System.out.print(a[i][right] + " ");
                right--;
            }
            if (top <= bottom) {
                for (int j = right; j >= left; j--)     // back along the top row
                    System.out.print(a[top][j] + " ");
                top++;
            }
        }
        System.out.println();
    }
}

Print a Matrix in Anticlockwise Spiral Order in Python

n = 4
a = [[i * n + j + 1 for j in range(n)] for i in range(n)]

top, bottom, left, right = 0, n - 1, 0, n - 1
result = []
while top <= bottom and left <= right:
    for i in range(top, bottom + 1):            # down the left column
        result.append(a[i][left])
    left += 1
    for j in range(left, right + 1):            # along the bottom row
        result.append(a[bottom][j])
    bottom -= 1
    if left <= right:
        for i in range(bottom, top - 1, -1):    # up the right column
            result.append(a[i][right])
        right -= 1
    if top <= bottom:
        for j in range(right, left - 1, -1):    # back along the top row
            result.append(a[top][j])
        top += 1
print(" ".join(str(x) for x in result))

Time and space complexity

Every element is read exactly once, so the traversal takes O(n²) time for an n × n matrix and O(1) extra memory (the Python version collects the result in a list).

Frequently asked questions

Does it work for rectangular matrices?

Yes. Use the number of rows for bottom and the number of columns for right; the loop and the checks stay the same.

Why are the if checks needed?

Without them, a 3 × 3 matrix would read its centre twice: once going down and once coming back. The checks make sure there is still a column or row left before reading it.

How is it different from the anticlockwise spiral matrix?

The anticlockwise spiral matrix writes numbers into a grid in this order. This program reads an existing grid in this order.

This tutorial was drafted with AI assistance. Spotted a mistake? Tell us and we fix it. Read our editorial policy.

Quick check: can you predict the output?

Answer from the code, then check. Every answer comes from the real output above.

Pattern 12 of 14 in Spiral Patterns

 

Still stuck? Ask AI to explain this code

Opens your favourite AI with this page, ready to explain every loop step by step.

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.

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.