# How to interchange diagonal elements of a matrix in C++

In this article, we are going to learn about How to interchange diagonal elements of a matrix in C++We will take the input from the user for the matrix elements, and then we will perform the switch on the diagonal elements of a matrix.

In this example, we are going to interchange diagonal elements of a matrix. We will ask the user to enter the values for each index, and once we have the matrices, then we will perform the switch on the diagonal elements of a matrix. The matrix that the user is providing must be a square matrix. Let us understand this with the help of the below code example.

### How to interchange diagonal elements of a matrix in C++

```#include<iostream>
using namespace std;
int main()
{
int Matrix;
int RowSize , ColumnSize;
int row, col;
long TempElements = 0;

cout<<"Enter Row and Column Size of the Matrix: ";
cin>>RowSize>>ColumnSize;

if(RowSize == ColumnSize)
{
cout<<"Please enter the Elements of the Matrix: ";
for(row=0; row< RowSize; row++)
{
for(col=0; col< ColumnSize; col++)
cin>> Matrix[row][col];
}

cout<<"The matrix inputted by the user is: \n";
for(row=0; row< RowSize; ++row)
{
for(col=0; col< ColumnSize; col++)
{
cout<<" "<<Matrix[row][col];
}
cout<<"\n";
}

for(row=0; row< RowSize; ++row)
{
TempElements = Matrix[row][row];
Matrix[row][row] = Matrix[row][RowSize - row - 1];
Matrix[row][RowSize - row - 1] = TempElements;
}

cout<<"The matrix after changing the diagonal elements is: \n";
for(row=0; row< RowSize; ++row)
{
for(col=0; col< ColumnSize; col++)
{
cout<<" "<<Matrix[row][col];
}
cout<<"\n";
}

}
else
cout<<"The size is not a Square Matrix  "<<"\n";

return 0;
}
```

Output

```Enter Row and Column Size of the Matrix: 3
3
Please enter the Elements of the Matrix: 1
2
3
4
5
6
7
8
9
The matrix inputted by the user is:
1 2 3
4 5 6
7 8 9
The matrix after changing the diagonal elements is:
3 2 1
4 5 6
9 8 7
```