Print a matrix in reverse spiral form
C program to print a matrix in reverse spiral form.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void read_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Element [%d][%d]\t:",i,j);
scanf("%d",&mat[i][j]);
}
}
}
void print_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
}
void print_antispiral(int mat[MAX][MAX], int row, int col)
{
int left, right, top, bottom, i;
int arr[MAX*MAX], count;
left = 0;
right = col-1;
top = 0;
bottom = row-1;
count = 0;
while(left <= right && top <= bottom)
{
for(i=left;i<=right;i++)
{
arr[count] = mat[top][i];
count++;
}
top++;
for(i=top;i<=bottom;i++)
{
arr[count] = mat[i][right];
count++;
}
right--;
if(top <= bottom)
{
for(i=right;i>=left;i--)
{
arr[count] = mat[bottom][i];
count++;
}
bottom--;
}
if(left <= right)
{
for(i=bottom;i>=top;i--)
{
arr[count] = mat[i][left];
count++;
}
left++;
}
}
for(i=count-1;i>=0;i--)
{
printf("%d ",arr[i]);
}
}
void main()
{
int mat[MAX][MAX];
int row, col;
printf("Enter the number of rows\t:");
scanf("%d",&row);
printf("Enter the number of columns\t:");
scanf("%d",&col);
printf("Enter the elements of the matrix\n");
read_matrix(mat, row, col);
printf("\nMatrix entered is\n");
print_matrix(mat, row, col);
printf("\nMatrix in antispiral form is \n");
print_antispiral(mat, row, col);
getch();
}
Output
Enter the number of rows :6
Enter the number of columns :4
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :2
Element [0][2] :3
Element [0][3] :4
Element [1][0] :5
Element [1][1] :6
Element [1][2] :7
Element [1][3] :8
Element [2][0] :9
Element [2][1] :10
Element [2][2] :11
Element [2][3] :12
Element [3][0] :13
Element [3][1] :14
Element [3][2] :15
Element [3][3] :16
Element [4][0] :17
Element [4][1] :18
Element [4][2] :19
Element [4][3] :20
Element [5][0] :21
Element [5][1] :22
Element [5][2] :23
Element [5][3] :24
Matrix entered is
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
21 22 23 24
Matrix in antispiral form is
10 14 18 19 15 11 7 6 5 9 13 17 21 22 23 24 20 16 12 8 4 3 2 1