Program to print matrix in Spiral form.
Solution in C PYTHON
#include<stdio.h>
int main() {
int mtrx[10][10], rows, cols, i, j, l, t, r, b;
scanf("%d %d",&rows,&cols);
for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
scanf("%d",&mtrx[i][j]);
l = 0;
t = cols-1;
r = rows-1;
b = 0;
i = 0;
while(i<rows*cols){
//The following loop reads left to right
//Constant row index, Increment column index
for(j=l;j<t+1;j++){
printf("%d ",mtrx[l][j]);
i+=1;
}
l+=1;
if(i==rows*cols)
break;
//The following loop reads top to bottom
//Increment row index, Constant column index
for(j=l;j<r+1;j++){
printf("%d ",mtrx[j][t]);
i+=1;
}
t-=1;
if(i==rows*cols)
break;
//The following loop reads right to left
//Constant row index, Decrement column index
for(j=t;j>b-1;j--){
printf("%d ",mtrx[r][j]);
i+=1;
}
r-=1;
if(i==rows*cols)
break;
//The following loop reads bottom to top
//Decrement row index, Constant column index
for(j=r;j>l-1;j--){
printf("%d ",mtrx[j][b]);
i+=1;
}
b+=1;
if(i==rows*cols)
break;
}
return 0;
}
int main() {
int mtrx[10][10], rows, cols, i, j, l, t, r, b;
scanf("%d %d",&rows,&cols);
for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
scanf("%d",&mtrx[i][j]);
l = 0;
t = cols-1;
r = rows-1;
b = 0;
i = 0;
while(i<rows*cols){
//The following loop reads left to right
//Constant row index, Increment column index
for(j=l;j<t+1;j++){
printf("%d ",mtrx[l][j]);
i+=1;
}
l+=1;
if(i==rows*cols)
break;
//The following loop reads top to bottom
//Increment row index, Constant column index
for(j=l;j<r+1;j++){
printf("%d ",mtrx[j][t]);
i+=1;
}
t-=1;
if(i==rows*cols)
break;
//The following loop reads right to left
//Constant row index, Decrement column index
for(j=t;j>b-1;j--){
printf("%d ",mtrx[r][j]);
i+=1;
}
r-=1;
if(i==rows*cols)
break;
//The following loop reads bottom to top
//Decrement row index, Constant column index
for(j=r;j>l-1;j--){
printf("%d ",mtrx[j][b]);
i+=1;
}
b+=1;
if(i==rows*cols)
break;
}
return 0;
}
Input
4 4
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
4 4
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