Printing the snake pattern in matrix is one of the basic problems . In various companies this question is asked how can you print the Snake pattern . Look the image below , this is how a snake pattern look.
First of all we traverse the row from left to right , but second time we traverse the row from right to left. Then left to right and we keep doing this until we traverse each row .
So we have implemented a java code to do this task.
#include <iostream>
void SnakePattern(int mat[4][3],int M,int N)
{
for (int i = 0; i < M; i++) {
if (i % 2 == 0) {
for (int j = 0; j < N; j++)
std::cout << mat[i][j] << " ";
}
else {
for (int j = N - 1; j >= 0; j--)
std::cout << mat[i][j] << " ";
}
}
}
int main() {
int mat[4][3] = { {1,3,4},{3,4,5},{7,2,0},{9,5,3}};
SnakePattern(mat,4,3);
return 0;
}
Output : 1,3,4,5,4,3,7,2,0,3,5,9