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 snake pattern from the last column in C Programming.
In C, printing a matrix in snake pattern from the last column means traversing the matrix row by row, alternating the direction of column traversal. For odd-numbered rows (index 0, 2, 4...), we print from right to left, and for even-numbered rows (index 1, 3, 5...), we print from left to right.
Syntax
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
// Even rows: right to left
for (int j = n - 1; j >= 0; j--) {
printf("%d ", arr[i][j]);
}
} else {
// Odd rows: left to right
for (int j = 0; j < n; j++) {
printf("%d ", arr[i][j]);
}
}
}
Example
Here's a complete program that demonstrates snake pattern printing starting from the last column −
#include <stdio.h>
int main() {
int n = 4;
int arr[4][4] = {
{100, 99, 98, 97},
{93, 94, 95, 96},
{92, 91, 90, 89},
{85, 86, 87, 88}
};
printf("Matrix:
");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%3d ", arr[i][j]);
}
printf("
");
}
printf("\nSnake pattern from last column: ");
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
// Even rows (0, 2, 4...): print right to left
for (int j = n - 1; j >= 0; j--) {
printf("%d ", arr[i][j]);
}
} else {
// Odd rows (1, 3, 5...): print left to right
for (int j = 0; j < n; j++) {
printf("%d ", arr[i][j]);
}
}
}
printf("
");
return 0;
}
Matrix: 100 99 98 97 93 94 95 96 92 91 90 89 85 86 87 88 Snake pattern from last column: 97 98 99 100 93 94 95 96 89 90 91 92 85 86 87 88
How It Works
- The algorithm uses the modulo operator
i % 2to determine the traversal direction - For even-indexed rows (0, 2, 4...), it starts from the last column and moves left
- For odd-indexed rows (1, 3, 5...), it starts from the first column and moves right
- This creates a snake-like zigzag pattern through the matrix
Conclusion
The snake pattern traversal from the last column efficiently prints matrix elements in a zigzag manner. This technique is useful in various matrix manipulation problems and demonstrates how simple conditional logic can create complex traversal patterns.
Advertisements
