Interchange the diagonal of a matrix in c++

C++ program for Interchange the diagonal of a matrix. Here more solutions.
// Include header file
#include <iostream>
#include <vector>
using namespace std;
// stdc++ 11 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
public :
static void swapDiagonal(vector<vector<int>> &matrix,
int x,
int y,
int p,
int q)
{
if (x >= y || p >= q) {
return;
}
int temp = 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 void showMatrix(vector<vector<int>> matrix, int size)
{
// iterate rows
for (int i = 0; i < size; ++i) {
// iterate columns
for (int j = 0; j < size; ++j) {
// Display element value
cout<<" " << matrix[i][j];
}
// include new line
cout<<endl;
}
// include new line
cout<<endl;
}
};
int main()
{
// Define matrix element
vector<vector<int>> matrix {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
// Assume N X N matrix
int n = matrix.size();
// Display element
Exchange::showMatrix(matrix, n);
// interchange request
Exchange::swapDiagonal(matrix, 0, n - 1, 0, n - 1);
// Display element
Exchange::showMatrix(matrix, n);
}
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
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.
New Comment