- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements