Print a matrix in Reverse Wave Form in C++



In this problem, we are given a matrix. Our task is to print the matrix in reverse waveform in a single line.

This example will make the problem clear,

Input:
   1 4 6 11
   2 5 8 54
   7 9 3 43
   1 7 4 34
Output: 11 54 43 34 4 3 8 6 4 5 9 7 1 7 2 1

To solve this problem, we have to print the reverse waveform of our matrix and for this, we will print the elements of the last column in the downward direction and then second-last column’s elements in upward and so on this the first column of the array.

Example

Program to show the implementation of our solution

 Live Demo

#include<iostream>
using namespace std;
#define R 4
#define C 4
void printReverseWaveForm(int m, int n, int arr[R][C]) {
   int i, j = n - 1, wave = 1;
   while (j >= 0) {
      if (wave == 1) {
         for (i = 0; i < m; i++)
            cout<<arr[i][j]<<" ";
         wave = 0;
         j--;
      } else {
         for (i = m - 1; i >= 0; i--)
            cout<<arr[i][j]<<" ";
         wave = 1;
         j--;
      }
   }
}
int main() {
   int arr[R][C] = {
      { 1, 5, 7, 98 },
      { 15, 22, 45, 12 },
      { 5, 10, 21, 34 },
      { 31, 24, 45, 60 }
   };
   cout<<"Reverse Wave Form of the given matrix :\n";
   printReverseWaveForm(R, C, arr);
   return 0;
}

Output

Reverse Wave Form of the given matrix −

98 12 34 60 45 21 45 7 5 22 10 24 31 5 15 1

Advertisements