Swift Program to Interchange the Diagonals of a Matrix


In this article, we will learn how to write a swift program to interchange the diagonals. Therefore, to interchange the diagonals we need to swap the elements of primary diagonal with the elements of secondary diagonal of the given matrix. For example −

Original matrix:
2 4 5 6 
3 4 6 2
6 7 7 2
1 1 1 1
So after swapping diagonals we get:
6 4 5 2
3 6 4 2
6 7 7 2
1 1 1 1

Algorithm

  • Step 1 − Create a function.

  • Step 2 − Run a for loop to iterate through each element.

  • Step 3 − Swap the elements of primary and secondary diagonals.

let temp = mxt[x][x]
mxt[x][x] = mxt[x][size-x-1]
mxt[x][size-x-1] = temp
  • Step 4 − Create a matrix.

  • Step 5 − Call the function and pass the matrix into it

  • Step 6 − Print the output.

Example

Following Swift program to interchange the diagonals.

import Foundation
import Glibc

// Size of the array 
var size = 3

// Function to interchange the diagonals of the matrix
func diagonalInterchange(M:[[Int]]){
   var mxt : [[Int]] = M
   
   // Interchanging diagonals by
   // swapping the elements
   for x in 0..<size{
      if (x != size/2){
         let temp = mxt[x][x]
         mxt[x][x] = mxt[x][size-x-1]
         mxt[x][size-x-1] = temp
      }
   }
   
   // Displaying matrix
   print("Matrix after diagonals interchange:")
   for m in 0..<size{
      for n in 0..<size{
         print(mxt[m][n], terminator: " ")
      }
      print("\n")
   }
}

// Creating 3x3 matrix of integer type
var matrix : [[Int]] = [[2, 3, 4], 
   [5, 6, 7], 
   [8, 3, 2]]

print("Original Matrix:")
for x in 0..<size{
   for y in 0..<size{
      print(matrix[x][y], terminator:" ")
   }
   print("\n")
}

// Calling the function 
diagonalInterchange(M:matrix)

Output

Original Matrix:
2 3 4 

5 6 7 

8 3 2 

Matrix after diagonals interchange:
4 3 2 

5 6 7 

2 3 8 

Here in the above code, we have a 3x3 square matrix. Now we create a function in which we run a for loop from 0 to size−1 and for each iteration we swap the elements of primary(mxt[x][x]) and secondary(mxt[x][size−x−1]) diagonals with each other using temporary variable and display the modified matrix.

Conclusion

Therefore, this is how we can interchange the diagonals of the given matrix. This method is applicable to any type of matrix−like square, symmetric, horizontal, etc.

Updated on: 29-Dec-2022

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements