#include <stdio.h>
#define COLS 4
#define ROWS 4
void PrintMatrixInSpiralForm(int matrix[][COLS]) {
int top = 0, bottom = COLS - 1;
int left = 0, right = ROWS - 1;
while (1) {
if (left > right) {
break;
}
// top row
for (int i = left; i <= right; i++) {
printf("%d ", matrix[top][i]);
}
printf("\n");
top++; // next row
if (top > bottom) {
break;
}
// right column
for (int i = top; i <= bottom; i++) {
printf("%d ", matrix[i][right]);
}
printf("\n");
right--; // previous column
if (left > right) {
break;
}
// bottom row
for (int i = right; i >= left; i--) {
printf("%d ", matrix[bottom][i]);
}
printf("\n");
bottom--; // previous row
if (top > bottom) {
break;
}
// left column
for (int i = bottom; i >= top; i--) {
printf("%d ", matrix[i][left]);
}
printf("\n");
left++; // next column
}
}
int main()
{
int matrix[ROWS][COLS] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
PrintMatrixInSpiralForm(matrix);
}
/*
run:
1 2 3 4
8 12 16
15 14 13
9 5
6 7
11
10
*/