This C++ program interchanges the diagonals of a square matrix. The square matrix is taken as an input and saved into a two-dimensional array which is initialized using new operator. The diagonals of the square are interchanged by changing the elements of the diagonal lying on same row at each iteration.

Here is the source code of the C++ program which interchanges the diagonals of a square matrix. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

`/*`

`* C++ Program to interchange the 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";

`}`

`}`

$ gcc test.cpp $ a.out 3 1 2 3 4 5 6 7 8 9 New Matrix 3 2 1 4 5 6 9 8 7

**Sanfoundry Global Education & Learning Series – 1000 C++ Programs.**

If you wish to look at all C++ Programming examples, go to C++ Programs.