
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Interchange Elements of First and Last Rows of a Matrix in Swift
In this article, we will learn how to write a swift program to interchange the elements of first and last in a matrix across rows. Therefore, to interchange the elements we need to swap the elements of the first row with the elements of the last row 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 rows we get: 1 1 1 1 3 4 6 2 6 7 7 2 2 4 5 6
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[0][x] mxt[0][x] = mxt[size-1][x] mxt[size-1][x] = 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 elements of first and last in a matrix across rows.
import Foundation import Glibc // Size of the array var size = 3 // Function to interchange the elements // of first and last rows func FirstLastInterchange(M:[[Int]]){ var mxt : [[Int]] = M // Interchanging the elements of first // and last rows by swapping for x in 0..<size{ let temp = mxt[0][x] mxt[0][x] = mxt[size-1][x] mxt[size-1][x] = temp } // Displaying matrix print("Matrix after first and last rows 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]] = [[11, 33, 44], [55, 66, 77], [88, 33, 22]] print("Original Matrix:") for x in 0..<size{ for y in 0..<size{ print(myMatrix[x][y], terminator:" ") } print("\n") } // Calling the function FirstLastInterchange(M:myMatrix)
Output
Original Matrix: 11 33 44 55 66 77 88 33 22 Matrix after first and last rows interchange: 88 33 22 55 66 77 11 33 44
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[0][x]) and last(mxt[size?1][x]) rows with each other using temporary variable and display the modified matrix.
Conclusion
So this is how we can interchange the elements of the first and last rows of the given matrix. This method is applicable to any type of matrix-like square, symmetric, horizontal, etc.