# Swift Program to Interchange Elements of First and Last Columns of Matrix

In this article, we will learn how to write a swift program to interchange the elements of first and last in a matrix across columns. Therefore, to interchange the elements we need to swap the elements of the first column with the elements of the last column 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 the first and last column we get:
6 4 5 2
2 4 6 3
2 7 7 6
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 the first and last columns.

let temp = mxt[x][0]
mxt[x][0] = mxt[x][size-1]
mxt[x][size-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 the Swift program to interchange the elements of first and last in a matrix across columns.

import Foundation
import Glibc

// Size of the array
var size = 3

// Function to interchange the elements
// of first and last column
func FirstLastColInterchange(M:[[Int]]){
var mxt : [[Int]] = M

// Interchanging the elements of first
// and last column by swapping
for x in 0..<size{
let temp = mxt[x][0]
mxt[x][0] = mxt[x][size-1]
mxt[x][size-1] = temp
}

// Displaying matrix
print("Matrix after first and last column 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 myMatrix : [[Int]] = [[10, 30, 40],
[50, 60, 70],
[80, 30, 20]]

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

// Calling the function
FirstLastColInterchange(M:myMatrix)


### Output

Original Matrix:
10 30 40

50 60 70

80 30 20

Matrix after first and last column interchange:
40 30 10

70 60 50

20 30 80


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 the first(mxt[x][0]) and last(mxt[x][size-1]) columns with each other using temporary variable and display the modified matrix.

## Conclusion

Therefore, this is how we can interchange the elements of the first and last columns of the given matrix. This method is applicable to any type of matrix-like square, symmetric, horizontal, etc.

Updated on: 29-Dec-2022

144 Views