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 in C Programming.
In C programming, printing a matrix in snake pattern means traversing the matrix row by row where even-indexed rows are printed from left to right and odd-indexed rows are printed from right to left. This creates a snake-like zigzag pattern through the matrix elements.
Syntax
for (i = 0; i < rows; i++) {
if (i % 2 == 0) {
// Print left to right for even rows
for (j = 0; j < cols; j++)
printf("%d ", arr[i][j]);
} else {
// Print right to left for odd rows
for (j = cols - 1; j >= 0; j--)
printf("%d ", arr[i][j]);
}
}
Algorithm
- Initialize − Create a 2D array with elements
- Iterate through rows − Use a loop from 0 to number of rows
- Check row index − If row index is even (i % 2 == 0)
- Print left to right − Traverse columns from 0 to N-1
- Print right to left − For odd rows, traverse columns from N-1 to 0
Example
#include <stdio.h>
#define M 4
#define N 4
int main() {
int i, j;
int arr[M][N] = {
{ 100, 99, 98, 97 },
{ 93, 94, 95, 96 },
{ 92, 91, 90, 89 },
{ 85, 86, 87, 88 }
};
printf("Matrix in snake pattern: ");
for (i = 0; i < M; i++) {
if (i % 2 == 0) {
// Even row: left to right
for (j = 0; j < N; j++)
printf("%d ", arr[i][j]);
} else {
// Odd row: right to left
for (j = N - 1; j >= 0; j--)
printf("%d ", arr[i][j]);
}
}
printf("<br>");
return 0;
}
Matrix in snake pattern: 100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85
Key Points
- Even-indexed rows (0, 2, 4...) are traversed from left to right
- Odd-indexed rows (1, 3, 5...) are traversed from right to left
- The pattern creates a continuous snake-like path through the matrix
- Time complexity is O(M × N) where M is rows and N is columns
Conclusion
The snake pattern traversal efficiently prints matrix elements in a zigzag manner by alternating the direction of traversal for each row. This technique is useful in matrix manipulation and spiral traversal problems.
Advertisements
