Swift Program to Print Matrix numbers containing in Z form

In this article, we will learn how to write a swift program to print a matrix in Z form. Here we traverse through the first row then the secondary diagonal and then the last row of the matrix to print the z form. For example,

4x4 Matrix −

$\mathrm{\begin{bmatrix}4 & 1 & 4 & 1 \newline1 & 3 & 1 & 3\newline2 & 1 & 1 & 2\newline1 & 6 & 6 & 1\end{bmatrix}}$

So the Z form numbers are −

$\mathrm{\begin{bmatrix}4 & 1 & 4 & 1 \newline & & 1 & \newline & 1 & & \newline1 & 6 & 6 & 1\end{bmatrix}}$

That will be represented as [4 1 4 1 1 1 1 6 6 1]

Algorithm

Step 1 − Declare the size of the matrix.

Step 2 −: Create a function.

Step 3 − In this function, print first row.

Step 4 − Print the diagonal.

Step 5 − Create a test matrix.

Step 6 − Call the function and pass the created matrix as a parameter in it.

Step 7 − Print the output.

Example

Following Swift program to print matrix in Z form.

import Foundation
import Glibc

// Size of the matrix
let size = 4

// Function to print square matrix in a Z form
func printZforMatrix(mxt:[[Int]]) {

// Printing first row
for x in 0..<size{
print(mxt[0][x], terminator: " ")
}

// Printing Secondary diagonal
var m = 1
var n = size-2
while(m < size && n >= 0) {
print(mxt[m][n], terminator: " ")
m += 1
n -= 1
}

// Printing last row
for x in 1..<size{
print(mxt[size-1][x], terminator: " ")
}
}

// Test matrix
var matrix1 = [[1, 0, 0, 2], [0, 1, 4, 0], [0, 6, 1, 0], [7, 1, 1, 1]]
printZforMatrix(mxt:matrix1)


Output

1 0 0 2 4 6 7 1 1 1


Here in the above code, we create a function to print the matrix in Z form. In this function, we iterate through each element of the given matrix, then first print the first row, then the secondary or second diagonal, and at last print the elements of the last row of the given matrix.

Conclusion

So this is how we can able print the matrix in Z form. Using the discussed method, we can print the Z form of any type of matrix-like 4x5, 6x6, etc.