Swift Program to calculate the sum of left diagonal of the 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 calculate the sum of the left diagonal of the square matrix using Swift Programming. A square matrix is a matrix in which the number of rows and columns are same. For example 2x2, 5x5, etc.

For example, we have the following matrix −

Matrix = 3 4 5 1
         5 3 2 2
         1 8 1 4
         5 6 3 2

The left diagonal elements are 3, 3, 1, 2. So, the sum of left diagonal is 9(3+3+1+2).

Algorithm

  • Step 1 − Create a function.

  • Step 2 − Create a variable named sum to store the sum. The initial value of sum = 0.

  • Step 3 − Run nested for-in loop to iterate through each row and column.

  • Step 4 − In this nested loop, add all left diagonal elements together and store the result into sum variable.

  • Step 5 − Return sum.

  • Step 6 − Create a square matrix and pass it in the function along with the size of the matrix.

  • Step 7 − Print the output.

Example

Following Swift program to print the sum of left diagonal of the matrix.

import Foundation
import Glibc

// Function to print the sum of left diagonal of the square matrix
func printLeftDiagonalSum(mxt:[[Int]], size: Int) -> Int {
   var sum = 0
   for x in 0..<size {
      for y in 0..<size {
         if (x == y) {
            sum += mxt[x][y]
         }
      }
   }
   return sum
}

// 4x4 square matrix
var M = [[2, 3, 4, 3], [1, 2, 4, 2], [5, 3, 1, 1], [4, 1, 4, 1]]

print("Matrix:")
for x in 0..<4 {
   for y in 0..<4 {
      print(M[x][y], terminator:" ")        
   }
   print()
}

// Calling the function and passing 
// the size of the square matrix
print("\nSum of the left diagonal elements is:", printLeftDiagonalSum(mxt: M, size: 4))

Output

Matrix:
2 3 4 3 
1 2 4 2 
5 3 1 1 
4 1 4 1 

Sum of the left diagonal elements is: 6

Here in the above code, we create a function to print the sum of the left diagonal of the 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 left diagonal elements(x==y). Then add all the elements together and return the sum that is 6.

Conclusion

So this is how we can calculate the sum of left diagonal of the matrix. Here this method only works for square matrix. If you want to use other type of matrix then you have to do some changes to the code.

Updated on: 19-Jul-2023

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements