C++ Program to Print Matrix in Z form?


Here we will see how to print the matrix elements in Z form. So if the array is like below −

5 8 7 1
2 3 6 4
1 7 8 9
4 8 1 5

Then it will be printed like: 5, 8, 7, 1, 6, 7, 4, 8, 1, 5

Algorithm

printMatrixZ(mat)

Begin
   print the first row
   i := 1, j := n-2
   while i < n and j >= 0, do
      print mat[i, j]
      i := i + 1, j := j - 1
   done
   print the last row
End

Example

#include<iostream>
#define MAX 4
using namespace std;
void printMatrixZ(int mat[][MAX], int n){
   for(int i = 0; i<n; i++){
      cout << mat[0][i] << " ";
   }
   int i = 1, j = n-2;
   while(i < n && j >= 0){
      cout << mat[i][j] << " ";
      i++;
      j--;
   }
   for(int i = 1; i<n; i++){
      cout << mat[n-1][i] << " ";
   }
}
main() {
   int matrix[][MAX] = {{5, 8, 7, 1},
      {2, 3, 6, 4},
      {1, 7, 8, 9},
      {4, 8, 1, 5}
   };
   printMatrixZ(matrix, 4);
}

Output

5 8 7 1 6 7 4 8 1 5

Updated on: 31-Jul-2019

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements