C++ Program to Interchange Diagonals of a Square Matrix
#include <iostream>
using namespace std;
int main() {
int size, swap;
cin >> size;
int ** matrix = new int*[size];
// initialising columns for each row
for(int i = 0; i < size; i++) {
matrix[i] = new int[size];
}
// taking value corresponding to each cell from input
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++) {
cin >> matrix[i][j];
}
}
// swapping the values of diagonals
for(int i = 0, j = 0, k = size - 1; j < size; j++, i++, k--) {
swap = matrix[j][i];
matrix[j][i] = matrix[j][k];
matrix[j][k] = swap;
}
// printing the values
cout << "New Matrix\n";
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
cout << matrix[i][j] << " ";
}
cout << "\n";
}
}
Output:
3
1 2 3
4 5 6
7 8 9
New Matrix
3 2 1
4 5 6
9 8 7
