C++ Program to Interchange Elements of First and Last Columns in Matrix
Interchanging elements of the first and last columns of a matrix involves swapping the elements of the first column with the corresponding elements of the last column.
Problem Statement
Given a matrix, interchange the elements of the first column with those of the last column.
Approach
- Initialization: Verify the matrix is valid (non-empty and has more than one column).
- Swapping Elements: Iterate through each row of the matrix and swap the elements of the first column with the corresponding elements of the last column.
Example
For a 3×3 matrix:
Matrix before interchange:
1 2 3
4 5 6
7 8 9
Matrix after interchange:
3 2 1
6 5 4
9 8 7
C++ Code Implementation
Here is a C++ program to interchange the elements of the first and last columns of a matrix:
#include <iostream>
#include <vector>
using namespace std;
// Function to interchange elements of the first and last columns of a matrix
void interchangeFirstLastColumns(vector<vector<int>>& matrix) {
int numRows = matrix.size();
int numCols = matrix[0].size();
if (numCols < 2) {
cout << “Matrix must have at least two columns to interchange.” << endl;
return;
}
for (int row = 0; row < numRows; ++row) {
swap(matrix[row][0], matrix[row][numCols – 1]);
}
}
// 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 columns
interchangeFirstLastColumns(matrix);
cout << “Matrix after interchange:” << endl;
printMatrix(matrix);
return 0;
}
Explanation
-
Function interchangeFirstLastColumns:
- Parameters: Takes a 2D vector (matrix).
- Validation: Checks if the matrix has at least two columns. If not, it outputs a message and returns.
- Swapping Elements: Uses a loop to iterate through each row, swapping the elements of the first column with the corresponding elements of the last column.
-
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 columns.
- Column Interchange: Calls the interchangeFirstLastColumns function to swap the first and last columns.
- Printing After Interchange: Prints the matrix after interchanging the columns.