C++ Program to Swap Rows of a Matrix

This C++ program interchanges the rows of a matrix. The program takes the the matrix from the input and interchanges the row numbers given from input. The changed matrix is finally printed.

Here is the source code of the C++ program which interchanges the rows of a 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 rows of a matrix
  3.  */
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. int main() {
  8.     int xsize, ysize, * swap;
  9.     int row1, row2;
  10.  
  11.     cout << "Enter the size of matrix : ";
  12.     cin >> ysize >> xsize;
  13.     int ** matrix = new int*[ysize];
  14.     // initialising columns for each row
  15.     for(int i = 0; i < ysize; i++) {
  16.         matrix[i] = new int[xsize];
  17.     }
  18.     // taking value corresponding to each cell from input
  19.     cout << "Enter the matrix\n";
  20.     for(int i = 0; i < ysize; i++) {
  21.         for(int j = 0; j < xsize; j++) {
  22.             cin >> matrix[i][j];
  23.         }
  24.     }
  25.     cout << "Enter the rows to be interchanged : ";
  26.     cin >> row1 >> row2;
  27.     // interchanging the rows
  28.     swap = matrix[row1 - 1];
  29.     matrix[row1 - 1] = matrix[row2 - 1];
  30.     matrix[row2 - 1] = swap;
  31.     // printing the values
  32.     cout << "New Matrix\n";
  33.     for(int i = 0; i < ysize; i++) {
  34.         for(int j = 0; j < xsize; j++) {
  35.             cout << matrix[i][j] << " ";
  36.         }
  37.         cout << "\n";
  38.     }
  39. }

$ gcc test.cpp
$ a.out
Enter the size of matrix : 3 3
Enter the matrix
1 2 3
4 5 6
7 8 9
Enter the rows to be interchanged : 1 2
New Matrix
4 5 6 
1 2 3 
7 8 9

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.