Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print matrix in zag-zag fashion in C Programming.
In C programming, printing a matrix in zig-zag fashion means traversing the matrix diagonally while alternating the direction of traversal. This creates a zig-zag pattern where elements are visited along diagonals, first from top-left to bottom-right, then from bottom-right to top-left, and so on.
Syntax
void printZigZag(int matrix[][COLS], int rows, int cols);
Example
Here's a complete program that prints a 3x3 matrix in zig-zag fashion −
#include <stdio.h>
#include <stdbool.h>
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
int main() {
int k = 3, l = 3;
int mat[][3] = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
int row = 0, col = 0;
bool flag = false;
int i, len, diag;
printf("Matrix in zig-zag fashion: ");
int mn = min(k, l);
/* Print first half of diagonals */
for (len = 1; len <= mn; ++len) {
for (i = 0; i < len; ++i) {
printf("%d ", mat[row][col]);
if (i + 1 == len)
break;
if (flag)
++row, --col;
else
--row, ++col;
}
if (len == mn)
break;
if (flag)
++row, flag = false;
else
++col, flag = true;
}
/* Move to next starting position */
if (row == 0) {
if (col == k - 1)
++row;
else
++col;
flag = true;
} else {
if (row == l - 1)
++col;
else
++row;
flag = false;
}
/* Print second half of diagonals */
int MAX = max(k, l) - 1;
for (diag = MAX; diag > 0; --diag) {
if (diag > mn)
len = mn;
else
len = diag;
for (i = 0; i < len; ++i) {
printf("%d ", mat[row][col]);
if (i + 1 == len)
break;
if (flag)
++row, --col;
else
++col, --row;
}
if (row == 0 || col == k - 1) {
if (col == k - 1)
++row;
else
++col;
flag = true;
} else if (col == 0 || row == l - 1) {
if (row == l - 1)
++col;
else
++row;
flag = false;
}
}
printf("<br>");
return 0;
}
Matrix in zig-zag fashion: 10 20 40 70 50 30 60 80 90
How It Works
The algorithm works in two phases:
- Phase 1: Traverse diagonals from top-left corner, increasing diagonal length until reaching the middle
- Phase 2: Continue from the appropriate edge position, decreasing diagonal length until reaching bottom-right
- The
flagvariable controls the direction of traversal within each diagonal - Direction alternates between each diagonal to create the zig-zag pattern
Conclusion
The zig-zag matrix traversal technique efficiently prints matrix elements diagonally with alternating directions. This approach is useful for various matrix processing problems and demonstrates advanced array indexing techniques in C programming.
Advertisements
