# Interchange the diagonal of a matrix in swift

Swift program for Interchange the diagonal of a matrix. Here mentioned other language solution.

``````import Foundation
/*
Swift 4 program for
Swap diagonal elements of matrix using recursion
*/
class Exchange
{
// Method which are perform swap operation
// Here x and y indicate start and end rows
// p and q indicates start and end columns
static func swapDiagonal(_ matrix: inout[[Int]],
_ x: Int, _ y: Int, _ p: Int, _ q: Int)
{
if (x >= y || p >= q)
{
return;
}
var temp: Int = matrix[x][p];
// Swap the element value
matrix[x][p] = matrix[x][q];
matrix[x][q] = temp;
temp = matrix[y][p];
// Swap the element value
matrix[y][p] = matrix[y][q];
matrix[y][q] = temp;
Exchange.swapDiagonal(&matrix, x + 1, y - 1, p + 1, q - 1);
}
// Display matrix elements
static func showMatrix(_ matrix: [[Int]],
_ size: Int)
{
var i: Int = 0;
// iterate rows
while (i < size)
{
var j: Int = 0;
// iterate columns
while (j < size)
{
// Display element value
print(" ",matrix[i][j], terminator: "");
j += 1;
}
//  include new line
print();
i += 1;
}
// include new line
print();
}
static func main()
{
// Define matrix element
var matrix: [
[Int]
] = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
// Assume N X N matrix
let n: Int = matrix.count;
// Display element
Exchange.showMatrix(matrix, n);
// interchange request
Exchange.swapDiagonal(&matrix, 0, n - 1, 0, n - 1);
// Display element
Exchange.showMatrix(matrix, n);
}
}
Exchange.main();``````

Output

``````  1  2  3  4
5  6  7  8
9  10  11  12
13  14  15  16

4  2  3  1
5  7  6  8
9  11  10  12
16  14  15  13
``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.