
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 matrix in alternate manner (left to right then right to left) in C++
In this problem, we are given a 2D array. Our task is to print all the elements of the array starting from the first row, from left to right, then right to left in the next row and again from left to right and so on.
Let’s take an example to understand the problem.
Input: array = { {2, 5} {4, 9} } Output: 2 5 9 4
To solve this problem, we will print elements in the given direction (LtoR and RtoL) of a row. And a flag element to show the direction of printing will switch after every iteration.
This is an easy and efficient solution with time complexity = O(R*C)
Example
Program to show the implementation of our solution
#include<iostream> using namespace std; #define R 3 #define C 3 void printAlternateMatrix(int arr[R][C]) { bool direction = true; for (int i=0; i<R; i++){ if (direction){ for (int j=0; j<C; j++) printf("%d ", arr[i][j]); } else{ for (int j=C-1; j>=0; j--) printf("%d ",arr[i][j]); } direction = !direction; } } int main() { int arr[][C] = { { 23 , 50 , 4 }, { 89 , 9 , 34 }, { 75 , 1 , 61 }, }; cout<<"Matrix in alternate order is :\n"; printAlternateMatrix(arr); return 0; }
Output
The matrix in alternate order is −
23 50 4 34 9 89 75 1 61
- Related Questions & Answers
- Position after taking N steps to the right and left in an alternate manner in C++
- Program to print right and left arrow patterns in C
- Print all palindromic paths from top left to bottom right in a matrix in C++
- CSS3 Left to right Gradient
- How to handle right-to-left and left-to-right swipe gestures on Android?
- Print all possible paths from top left to bottom right of a mXn matrix in C++
- How to handle right-to-left and left-to-right swipe gestures on iOS App?
- How to handle right-to-left and left-to-right swipe gestures on Android using Kotlin?
- Print all paths from top left to bottom right in a matrix with four moves allowed in C++
- Print all leaf nodes of a binary tree from right to left in C++
- Create Left to Right slide animation in Android?
- How to handle right to left swipe gestures?
- Left Shift and Right Shift Operators in C/C++
- Left right subarray sum product - JavaScript
- Bitwise Right/ left shift numbers in Arduino
Advertisements