Swift Program to calculate the sum of right diagonal of the matrix


A matrix is an arrangement of numbers in rows and columns. A matrix has two diagonals i.e. Right diagonal and Left diagonal. So here we calculate the sum of the right diagonal of the square matrix using Swift Programming.

For example, we have the following matrix −

Matrix = 3 4 5 
         5 3 2
         1 8 1

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

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 right 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 right diagonal of the matrix.

import Foundation
import Glibc

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

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

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

// Calling the function and passing 
// the size of the square matrix
print("\nSum of the right diagonal elements is:", printRightDiagonalSum(mxt: M, size: 3))

Output

Matrix:
2 3 4 
1 2 4 
5 3 1 

Sum of the right diagonal elements is: 11

Here in the above code, we create a function to print the sum of the right 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 3, means number of rows = 3 and number of columns = 3. 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 right diagonal elements((x+y)==(S-1)). Then add all the elements together and return the sum that is 11.

Conclusion

So this is how we can calculate the sum of right 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

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements