Note : Actually the question is to print diagonal of the matrix in zigzag way Given a 2D matrix, print all elements of the given matrix in diagonal order. For example, consider the following 5 X 4 input matrix.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
Diagonal printing of the above matrix is
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20
Now i'm just printing the subscripts of the array
#include<stdio.h>
#include<stdlib.h>
int main(){
int rows,cols,ind,inner,outer;
scanf("%d %d",&rows,&cols);
int **ptr=(int**)malloc(rows*sizeof(int*));
for(ind=0;ind<rows;ind++)
*(ptr+ind)=(int*)malloc(cols*sizeof(int));
for(outer=0;outer<cols;outer++){
for(inner=0;inner<rows;inner++){
scanf("%d ",(*(ptr+outer)+inner));
}
}
inner=0,outer=0;
for(ind=1;ind<rows+cols;ind++){
printf("%d",ind);
while(*(*(ptr+outer)+inner)!=0) {
printf("%d %d",outer,inner);
inner++;
outer--;
}printf("\n");
}
return 0;
}
Also for Arrays without malloc
#include<stdio.h>
#include<stdlib.h>
int main(){
int rows,cols,ind,inner,outer;
scanf("%d %d",&rows,&cols);
int arr[rows][cols];
for(outer=0;outer<rows;outer++){
for(inner=0;inner<cols;inner++){
scanf("%d ",&arr[outer][inner]);
}
}
inner=0,outer=0;
for(ind=0;ind<rows;ind++){
printf("%d",ind);
while(arr[outer][inner]){
//printf("%d %d",outer,inner);
inner++;
outer--;
}
printf("\n");
outer=ind;
inner=0;
}
return 0;
}