This is a C++ Program to Accept a Matrix and Interchange the Diagonals.
The program takes a square matrix and interchanges the diagonals.
1. The program takes a square matrix.
2. Using a for loop, the right and left diagonals are interchanged.
3. The result is printed.
4. Exit.
Here is the source code of C++ Program to Accept a Matrix and Interchange the Diagonals. The program output is shown below.
#include<iostream>
using namespace std;
int main ()
{
int i, j, m, n, x, A[10][10];
cout << "Enter number of rows and columns : ";
cin >> m >> n;
if (m != n)
{
cout << "Matrix is not a square matrix!";
exit(0);
}
cout << "Enter elements of matrix : ";
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
cin >> A[i][j];
cout << "Matrix : \n ";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
cout << A[i][j] << " ";
cout << "\n ";
}
for (i = 0; i < m; i++)
{
x = A[i][i];
A[i][i] = A[i][m - i - 1];
A[i][m - i - 1] = x;
}
cout << "\nMatrix after changing the diagonals : \n ";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
cout << A[i][j] << " ";
cout << "\n ";
}
return 0;
}
1. The user is asked to enter the number of rows and columns of the matrix. If they are not equal, program is exited.
2. The elements of the matrix are asked to enter and stored in ‘A’.
3. The entered matrix is displayed.
4. Using a for loop, elements of left and right diagonals are exchanged.
5. The resultant matrix is then printed.
Case 1 : Enter number of rows and columns : 2 2 Enter elements of matrix : 1 2 3 4 Matrix : 1 2 3 4 Matrix after changing the diagonals : 2 1 4 3 Case 2 : Enter number of rows and columns : 2 3 Matrix is not a square matrix! Case 3 : Enter number of rows and columns : 3 3 Enter elements of matrix : 9 8 7 6 5 4 3 2 1 Matrix : 9 8 7 6 5 4 3 2 1 Matrix after changing the diagonals : 7 8 9 6 5 4 1 2 3
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Apply for C++ Internship
- Check C++ Books
- Practice Programming MCQs
- Check Computer Science Books
- Apply for Computer Science Internship