Hello folks, This nitty problem is haunting me today. Here is the code I have written, but am not getting the expected output.
This is a program for printing matrix in spiral order.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int rows,cols,i,j;
int tr=0,rc,br,lc=0;
/*
tr = top row index.
rc = right column index.
br = bottom row index.
lc = left column index.
*/
scanf("%d%d", &rows,&cols);
br=rows-1; rc=cols-1;
int *ptr=(int*)calloc((rows*cols),sizeof(int));
for(i=0; i<rows; i++){
for(j=0; j<cols; j++){
scanf("%d", ((ptr+i*rows)+j));
}
}
while(br!=0 && rc!=0){
for(i=tr; i<rc; i++){
printf("%d ", *((ptr+tr*cols)+i)); // Top row.
}
for(i=tr; i<br; i++){
printf("%d ", *((ptr+i*cols)+rc)); // Right column.
}
for(i=rc; i>lc; i--){
printf("%d " , *((ptr+br*cols)+i)); // Bottom row.
}
for(i=rc; i>tr; i--){
printf("%d ", *((ptr+i*cols)+lc)); // Left column.
}
tr++; // Going Down.
rc--; // Shifting Left.
br--; // Going up.
lc++; // Shifting Right.
}
return 0;
}
And, here is the ouput.
Regards.