Print a given matrix in zigzag form in C++


In this problem, we are given a 2-dimensional matrix. Our task is to print the zigzag form of the matrix.

Let’s take an example to understand the problem

Input:
   12 99 43
   10 82 50
   15 75 5
Output: 12 99 43 50 82 10 15 75 5

To solve this problem, we will print the elements of the array in both directions (LtoR and RtoL). And change the direction using the flag variable.

Example

 Live Demo

#include <iostream>
using namespace std;
void printZigZagPattern(int row, int col, int a[][5]) {
   int evenRow = 0;
   int oddRow = 1;
   while (evenRow<ow) {
      for (int i=0;i<col;i++) {
         cout<<a[evenRow][i]<<" ";
      }
      evenRow = evenRow + 2;
      if(oddRow < row) {
         for (int i=col-1; i>=0; i--)
            cout<<a[oddRow][i] <<" ";
      }
      oddRow = oddRow + 2;
   }
}
int main() {
   int r = 3, c = 3;
   int mat[][5] = {
      {12,99,43},
      {10,82,50},
      {15,75,5}
   };
   cout<<"Elements of the matrix in ZigZag manner :\n";
   printZigZagPattern(r , c , mat);
   return 0;
}

Output

Elements of the matrix in a ZigZag manner −

12 99 43 50 82 10 15 75 5

Updated on: 27-Jan-2020

459 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements