Program to print matrix in counter clockwise direction.
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]);
t = 0;
b = rows-1;
l = 0;
r = cols-1;
i = 0;
while(i<rows*cols){
//The following loop reads top to bottom
//Increment row index, Constant column index
for(j=t;j<b+1;j++){
printf("%d ",mtrx[j][t]);
i+=1;
}
t+=1;
if(i==rows*cols)
break;
//The following loop reads left to right
//Constant row index, Increment column index
for(j=t;j<r+1;j++){
printf("%d ",mtrx[b][j]);
i+=1;
}
b-=1;
if(i==rows*cols)
break;
//The following loop reads bottom to top
//Decrement row index, Constant column index
for(j=b;j>l-1;j--){
printf("%d ",mtrx[j][r]);
i+=1;
}
r-=1;
if(i==rows*cols)
break;
//The following loop reads right to left
//Constant row index, Decrement column index
for(j=r;j>t-1;j--){
printf("%d ",mtrx[l][j]);
i+=1;
}
l+=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]);
t = 0;
b = rows-1;
l = 0;
r = cols-1;
i = 0;
while(i<rows*cols){
//The following loop reads top to bottom
//Increment row index, Constant column index
for(j=t;j<b+1;j++){
printf("%d ",mtrx[j][t]);
i+=1;
}
t+=1;
if(i==rows*cols)
break;
//The following loop reads left to right
//Constant row index, Increment column index
for(j=t;j<r+1;j++){
printf("%d ",mtrx[b][j]);
i+=1;
}
b-=1;
if(i==rows*cols)
break;
//The following loop reads bottom to top
//Decrement row index, Constant column index
for(j=b;j>l-1;j--){
printf("%d ",mtrx[j][r]);
i+=1;
}
r-=1;
if(i==rows*cols)
break;
//The following loop reads right to left
//Constant row index, Decrement column index
for(j=r;j>t-1;j--){
printf("%d ",mtrx[l][j]);
i+=1;
}
l+=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 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output
1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7