C++ Program to Interchange Diagonals of a Square Matrix

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.

  1. /*
  2.  * C++ Program to interchange the diagonals of a square matrix
  3.  */
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. int main() {
  8.     int size, swap;
  9.  
  10.     cin >> size;
  11.     int ** matrix = new int*[size];
  12.     // initialising columns for each row
  13.     for(int i = 0; i < size; i++) {
  14.         matrix[i] = new int[size];
  15.     }
  16.     // taking value corresponding to each cell from input
  17.     for(int i = 0; i < size; i++)
  18.     {
  19.         for(int j = 0; j < size; j++) {
  20.             cin >> matrix[i][j];
  21.         }
  22.     }
  23.     // swapping the values of diagonals
  24.     for(int i = 0, j = 0, k = size - 1; j < size; j++, i++, k--) {
  25.         swap = matrix[j][i];
  26.         matrix[j][i] = matrix[j][k];
  27.         matrix[j][k] = swap;
  28.     }
  29.     // printing the values
  30.     cout << "New Matrix\n";
  31.     for(int i = 0; i < size; i++) {
  32.         for(int j = 0; j < size; j++) {
  33.             cout << matrix[i][j] << " ";
  34.         }
  35.         cout << "\n";
  36.     }
  37. }

$ 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.

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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.