# Print Matrix in zig-zag order

“** Print Matrix in zig-zag order**” is a a problem of printing the given matrix of size N*M in zig-zag order.

The zig-zag order of the matrix is traversing the first row of matrix from left to right, next row from right to left, next row from left to right and so on.

*Example:*

1 2 3 4 5 6 7 8 9Input:1 2 3 6 5 4 7 8 9OUTPUT:

**C++ Program to Print matrix in Zig-Zag Order is as follows:**

#include<bits/stdc++.h> using namespace std; int main() { int N,M; // Scan Dimensions of the matrix cout<<"Enter the dimension of the matrix:\n"; cin>>N>>M; int matrix[N][M]; // Scan Matrix Elements cout<<"Enter the elements of the matrix:\n"; for(int i = 0 ; i < N ; i++) for(int j = 0 ; j < M ; j++) cin>>matrix[i][j]; // Print the matrix in Zig-Zag Order cout<<"The Zig-zag traversal of the matrix is:\n"; for(int i = 0 ; i < N ; i++) { if(i%2==0) { for(int j = 0 ; j < M ; j++) cout<<matrix[i][j]<<" "; } else { for(int j = M-1 ; j>=0 ; j--) cout<<matrix[i][j]<<" "; } } }

Enter the dimension of the matrix: 3 3 Enter the elements of the matrix: 1 2 3 4 5 6 7 8 9 The Zig-zag traversal of the matrix is: 1 2 3 6 5 4 7 8 9OUTPUT:

**Related Posts:**

**Program to print matrix in spiral order.****Program to sort a matrix.****Program to Add two Matrix.****Program to Transpose a Matrix.****Program to Multiply Two Matrix.****Program to check Identity Matrix.****Program to check Idempotent Matrix.****Program to check Involuntary Matrix.****Infix to Postfix Conversion****Infix to Prefix Conversion****Prefix to Infix Conversion****Prefix to Postfix Conversion****Postfix to Infix Conversion****Postfix to Prefix Conversion****Check whether given Parentheses String are Balanced Parentheses or Not.****Next Greater Element****Find Minimum number of bracket reversals required to make an expression balanced.****Implement Queue Using Two Stacks.****Merge Overlapping Intervals using Stacks****Largest Rectangular Area in Histogram**