# C++ Program to Print Matrix in Z form?

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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[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