Swift Program to print the left diagonal matrix


In this article, we will learn how to write a swift program to print the left diagonal matrix.

A matrix is an arrangement of numbers in rows and columns. Matrix can be of various type like square matrix, horizontal matrix, vertical matrix etc. So here we print the left diagonal of square matrix. Square matrix is a matrix in which the number of rows and columns are same. For example 3x3, 5x5, 7x7, etc.

Algorithm

Step 1 − Create a function.

Step 2 − Run for-in loop to iterate through each element of the matrix.

Step 3 − Check if the row and column indices are the same.

Step 4 − If the element are diagonal elements, then print 2. Otherwise. Print 0.

Step 5 − Call the function and pass the matrix size to it.

Example

Following Swift program to print the left diagonal matrix.

import Foundation
import Glibc

// Function to print the left diagonal matrix
func printLeftDiagonal(S: Int) {
   for x in 0..<S  {
      for y in 0..<S  {
         if x == y {
            print("2", terminator: " ")
         }
         else {
            print("0", terminator: " ")
         }
      }
      print()
   }
}

// Calling the function and passing

// the size of the square matrix
printLeftDiagonal(S: 5)

Output

2 0 0 0 0
0 2 0 0 0
0 0 2 0 0
0 0 0 2 0
0 0 0 0 2

Conclusion

Here in the above code, we create a function to print the left diagonal square matrix. As we know the that the size of rows and columns are same, so in our case the size is 4, means number of rows = 4 and number of columns = 4. So in this function, we use nested for-in loop which iterates through each row and column. Then check if the row and column indices are same that is for the diagonal elements. If yes then this function print 2. Otherwise print 0. So this is how we can print the left diagonal matrix. Here this method works only for square matrix not for other matrix like 4x5, 6x8, etc.

Updated on: 16-Feb-2023

370 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements