Interchanging elements of the first and last rows of a matrix involves swapping the elements of the first row with the corresponding elements of the last row.
Problem Statement
Given a matrix, interchange the elements of the first row with those of the last row.
Approach
- Initialization: Verify the matrix is valid (non-empty and has more than one row).
- Swapping Elements: Iterate through each column of the matrix and swap the elements of the first row with the corresponding elements of the last row.
Example
For a 3×3 matrix:
Matrix before interchange:
1 2 3
4 5 6
7 8 9
Matrix after interchange:
7 8 9
4 5 6
1 2 3
C++ Code Implementation
Here is a C++ program to interchange the elements of the first and last rows of a matrix:
#include <iostream>
#include <vector>
using namespace std;
// Function to interchange elements of the first and last rows of a matrix
void interchangeFirstLastRows(vector<vector<int>>& matrix) {
int numRows = matrix.size();
if (numRows < 2) {
cout << “Matrix must have at least two rows to interchange.” << endl;
return;
}
int numCols = matrix[0].size();
for (int col = 0; col < numCols; ++col) {
swap(matrix[0][col], matrix[numRows – 1][col]);
}
}
// Function to print a matrix
void printMatrix(const vector<vector<int>>& matrix) {
for (const auto& row : matrix) {
for (const auto& elem : row) {
cout << elem << ” “;
}
cout << endl;
}
}
int main() {
// Initializing a 3×3 matrix
vector<vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
cout << “Matrix before interchange:” << endl;
printMatrix(matrix);
// Interchanging the first and last rows
interchangeFirstLastRows(matrix);
cout << “Matrix after interchange:” << endl;
printMatrix(matrix);
return 0;
}
Explanation
-
Function interchangeFirstLastRows:
- Parameters: Takes a 2D vector (matrix).
- Validation: Checks if the matrix has at least two rows. If not, it outputs a message and returns.
- Swapping Elements: Uses a loop to iterate through each column, swapping the elements of the first row with the corresponding elements of the last row.
-
Function printMatrix:
- Parameters: Takes a 2D vector (matrix).
- Printing: Iterates through the matrix and prints its elements in a formatted manner for better visualization.
-
Main Function:
- Matrix Initialization: Creates a sample 3×3 matrix.
- Printing Before Interchange: Prints the matrix before interchanging the rows.
- Row Interchange: Calls the interchangeFirstLastRows function to swap the first and last rows.
-
Printing After Interchange: Prints the matrix after interchanging the rows.