Question: Write a program in C to print the given matrix in spiral order.
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Printing a matrix in spiral order can be better understood by the following image.
Thus, printing a matrix in spiral order is just a way to traverse the matrix. The matrix can be supposed to be represented by a 2-D array.
#include<stdio.h> void spiralPrint(int m, int n, int a[][n]) { int i, k = 0, l = 0; m--, n--; while(k <= m && l <= n) { // Print the row left to right for(i = l; i <= n; ++i) { printf("%d ", a[k][i]); } // Print the column top to bottom k++; for(i = k; i <= m; ++i) { printf("%d ", a[i][n]); } // Print the row right to left n--; if(m >= k) { for(i = n; i >= l; --i) { printf("%d ", a[m][i]); } m--; } // Print the column bottom to top for(i = m; i >= k; --i) { printf("%d ", a[i][l]); } l++; } printf("\n"); } int main(void) { int arr[4][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; spiralPrint(4, 4, arr); return 0; }