
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Print a given matrix in reverse spiral form in C++
- Java program to print a given matrix in Spiral Form.
- Print a given matrix in counter-clockwise spiral form in C++
- Print matrix in antispiral form
- Print a matrix in Reverse Wave Form in C++
- Python Program to Print Matrix in Z form
- C++ Program to Print Matrix in Z form?
- Java Program to Print Matrix in Z form
- Zigzag (or diagonal) traversal of Matrix in C++
- Print a matrix in a spiral form starting from a point in C++
- Swift Program to Print Matrix numbers containing in Z form
- Program to Print the Squared Matrix in Z form in C
- How to print number of islands in a given matrix using C#?
- Print lower triangular matrix pattern from given array in C Program.
- Print maximum sum square sub-matrix of given size in C Program.

Advertisements