I want to traverse a matrix in zig-zag fashion.

Say my matrix is

I want my output to beCode:a11 a12 a13 a14 a21 a22 a23 a24 a31 a32 a33 a34 a41 a42 a43 a44

Here's how I tried to implement this :Code:a11 a12 a21 a31 a22 a13 a14 a23 a32 a41 a42 a33 a24 a34 a43 a44.

For the upper triangle of the matrix,

(start at 0, 0)

1. move right once

2. move to the bottom left

3. move down once

4. move to the top right.

For the lower triangle of the matrix,

1. move right once

2. move to the top right

3. move down once

4. move to the bottom left.

The code for this works fine but it looks a bit messy and I think it can be optimized. Here's my code for an 8x8 matrix.

Please let me know if theres a better way to do this and how I can improve on my code.Code:void zigzagOrder() { int i = 0; int j = 0; //for upper triangle of matrix printf("%d, %d\t", i, j); do { j++; printf("\n"); printf("%d, %d\t", i, j); while(j!=0) { i++; j--; printf("%d, %d\t", i, j); } i++; if(i>7) { i--; break; } printf("\n"); printf("%d, %d\t", i, j); while(i!=0) { i--; j++; printf("%d, %d\t", i, j); } } while(true); //for lower triangle of matrix do { j++; printf("\n"); printf("%d, %d\t", i, j); while(j!=7) { j++; i--; printf("%d, %d\t", i, j); } i++; if(i>7) { i--; break; } printf("\n"); printf("%d, %d\t", i, j); while(i!=7) { i++; j--; printf("%d, %d\t", i, j); } } while(true); }

Thanks