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.

`/*`

`* C++ Program to interchange the rows of a matrix`

`*/`

`#include <iostream>`

using namespace std;

int main() {

int xsize, ysize, * swap;

int row1, row2;

cout << "Enter the size of matrix : ";

cin >> ysize >> xsize;

int ** matrix = new int*[ysize];

`// initialising columns for each row`

for(int i = 0; i < ysize; i++) {

matrix[i] = new int[xsize];

`}`

`// taking value corresponding to each cell from input`

cout << "Enter the matrix\n";

for(int i = 0; i < ysize; i++) {

for(int j = 0; j < xsize; j++) {

cin >> matrix[i][j];

`}`

`}`

cout << "Enter the rows to be interchanged : ";

cin >> row1 >> row2;

`// interchanging the rows`

swap = matrix[row1 - 1];

matrix[row1 - 1] = matrix[row2 - 1];

matrix[row2 - 1] = swap;

`// printing the values`

cout << "New Matrix\n";

for(int i = 0; i < ysize; i++) {

for(int j = 0; j < xsize; j++) {

cout << matrix[i][j] << " ";

`}`

cout << "\n";

`}`

`}`

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

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