# C++ Program to Print Matrix in Z form

Given a square matrix of order n*n, we need to print elements of the matrix in Z form

Examples: Input : mat[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : 1 2 3 5 7 8 9 Input : mat[][] = {5, 19, 8, 7, 4, 1, 14, 8, 2, 20, 1, 9, 1, 2, 55, 4} Output: 5 19 8 7 14 20 1 2 55 4

`// CPP program to print a square matrix in Z form` `#include <bits/stdc++.h>` `using` `namespace` `std;` `const` `int` `MAX = 100;` ` ` `// Function to print a square matrix in Z form` `void` `printZform(` `int` `mat[][MAX], ` `int` `n)` `{` ` ` `// print first row` ` ` `for` `(` `int` `i = 0; i < n; i++)` ` ` `cout << mat[0][i] << ` `" "` `;` ` ` ` ` `// Print diagonal` ` ` `int` `i = 1, j = n - 2;` ` ` `while` `(i < n && j >= 0) ` `// print diagonal` ` ` `{` ` ` `cout << mat[i][j] << ` `" "` `;` ` ` `i++;` ` ` `j--;` ` ` `}` ` ` ` ` `// Print last row` ` ` `for` `(` `int` `i = 1; i < n; i++)` ` ` `cout << mat[n - 1][i] << ` `" "` `;` `}` ` ` `// Driver function` `int` `main()` `{` ` ` `int` `mat[][MAX] = { { 4, 5, 6, 8 },` ` ` `{ 1, 2, 3, 1 },` ` ` `{ 7, 8, 9, 4 },` ` ` `{ 1, 8, 7, 5 } };` ` ` `printZform(mat, 4);` ` ` `return` `0;` `}` |

**Output:**

4 5 6 8 3 8 1 8 7 5

Please refer complete article on Program to Print Matrix in Z form for more details!

Want to learn from the best curated videos and practice problems, check out the

**C++ Foundation Course**for Basic to Advanced C++ and**C++ STL Course**for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer**Complete Interview Preparation Course****.**