Print matrix in antispiral form

In C programming, printing a matrix in antispiral form means traversing the matrix in a spiral order (clockwise from outside to inside) and then displaying the elements in reverse order. This creates an "antispiral" pattern where we start from the center and work outward.

Syntax

// Using array to store spiral elements
int spiral[n*n];
// Traverse in spiral order: right ? down ? left ? up
// Print in reverse order

Algorithm

The approach involves two main steps −

  1. Spiral Traversal: Traverse the matrix in spiral order (right ? down ? left ? up) and store elements in an array
  2. Reverse Print: Print the stored elements in reverse order to achieve antispiral effect
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Spiral: 1?2?3?4?8?12?16?15?14?13?9?5?6?7?11?10 Antispiral: 10?11?7?6?5?9?13?14?15?16?12?8?4?3?2?1

Example

Here's a complete implementation to print a 4x4 matrix in antispiral form −

#include <stdio.h>

int main() {
    int mat[4][4] = {{1, 2, 3, 4},
                     {5, 6, 7, 8},
                     {9, 10, 11, 12},
                     {13, 14, 15, 16}};
    
    int spiral[16];
    int index = 0;
    int top = 0, bottom = 3, left = 0, right = 3;
    
    printf("Original Matrix:
"); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { printf("%d ", mat[i][j]); } printf("
"); } // Spiral traversal while(top <= bottom && left <= right) { // Right direction for(int i = left; i <= right; i++) { spiral[index++] = mat[top][i]; } top++; // Down direction for(int i = top; i <= bottom; i++) { spiral[index++] = mat[i][right]; } right--; // Left direction if(top <= bottom) { for(int i = right; i >= left; i--) { spiral[index++] = mat[bottom][i]; } bottom--; } // Up direction if(left <= right) { for(int i = bottom; i >= top; i--) { spiral[index++] = mat[i][left]; } left++; } } // Print in reverse (antispiral) printf("Antispiral Form: "); for(int i = index - 1; i >= 0; i--) { printf("%d ", spiral[i]); } printf("
"); return 0; }
Original Matrix:
1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14 15 16 
Antispiral Form: 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1

How It Works

  1. Boundary Setup: Initialize top, bottom, left, right boundaries
  2. Spiral Traversal: Move right ? down ? left ? up, adjusting boundaries after each direction
  3. Store Elements: Store each traversed element in the spiral array
  4. Reverse Print: Print the spiral array from last index to first

Conclusion

The antispiral form of a matrix is achieved by performing spiral traversal and then reversing the order of elements. This technique demonstrates both spiral matrix traversal and array reversal concepts in C programming.

Updated on: 2026-03-15T11:05:58+05:30

492 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements