Open In App

Program to Interchange or Swap Columns in a Matrix

Last Updated : 11 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a matrix having m rows and n columns, the task is to write a program to interchange any two Columns(i.e. column no. N and M given in the input) in the given matrix. 

Example:

Input : N = 1, M = 2, mat[][] = {{2, 1, 4}, {1, 2, 3}, {3, 6, 2}}
Output: mat[][] = {{1, 2, 4}, {2, 1, 3}, {6, 3, 2}}

Input : N = 1, M = 1, mat[][] = {{2, 1, 4}, {1, 2, 3}}
Output: mat[][] = {{2, 1, 4}, {1, 2, 3}}

Approach:

One of the most easy method by which columns can be swapped is using a temporary array.

  • Store the element of column N into the temporary array
  • Replace elements at column N with elements of column M
  • Replace the elements of column M with elements of temporary array

Below is the code implementation for the above approach:

C++




#include <iostream>
#include <vector>
 
void swapColumns(std::vector<std::vector<int> >& matrix,
                 int col1, int col2)
{
    if (col1 == col2) {
        return; // No need to swap if columns are the same
    }
 
    int num_rows = matrix.size();
 
    for (int row = 0; row < num_rows; row++) {
        // Swap elements at col1 and col2 using a temporary
        // variable
        int temp = matrix[row][col1];
        matrix[row][col1] = matrix[row][col2];
        matrix[row][col2] = temp;
    }
}
 
void printMatrix(
    const std::vector<std::vector<int> >& matrix)
{
    for (const std::vector<int>& row : matrix) {
        for (int element : row) {
            std::cout << element << ' ';
        }
        std::cout << std::endl;
    }
}
 
int main()
{
    std::vector<std::vector<int> > matrix
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
    std::cout << "Original Matrix:" << std::endl;
    printMatrix(matrix);
 
    int col1 = 0; // Column 1 to swap
    int col2 = 2; // Column 2 to swap
 
    if (0 <= col1 && col1 < matrix[0].size() && 0 <= col2
        && col2 < matrix[0].size()) {
        swapColumns(matrix, col1, col2);
        std::cout << "\nMatrix after swapping columns:"
                  << std::endl;
        printMatrix(matrix);
    }
    else {
        std::cout << "Invalid column indices for swapping."
                  << std::endl;
    }
 
    return 0;
}


Java




import java.util.Arrays;
 
public class MatrixColumnSwap {
    public static void swapColumns(int[][] matrix, int col1,
                                   int col2)
    {
        if (col1 == col2) {
            return; // No need to swap if columns are the
                    // same
        }
 
        int num_rows = matrix.length;
 
        for (int row = 0; row < num_rows; row++) {
            // Swap elements at col1 and col2 using a
            // temporary variable
            int temp = matrix[row][col1];
            matrix[row][col1] = matrix[row][col2];
            matrix[row][col2] = temp;
        }
    }
 
    public static void printMatrix(int[][] matrix)
    {
        for (int[] row : matrix) {
            for (int element : row) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }
 
    public static void main(String[] args)
    {
        int[][] matrix
            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
        System.out.println("Original Matrix:");
        printMatrix(matrix);
 
        int col1 = 0; // Column 1 to swap
        int col2 = 2; // Column 2 to swap
 
        if (0 <= col1 && col1 < matrix[0].length
            && 0 <= col2 && col2 < matrix[0].length) {
            swapColumns(matrix, col1, col2);
            System.out.println(
                "\nMatrix after swapping columns:");
            printMatrix(matrix);
        }
        else {
            System.out.println(
                "Invalid column indices for swapping.");
        }
    }
}


Python3




def swap_columns(matrix, col1, col2):
    if col1 == col2:
        return  # No need to swap if columns are the same
 
    num_rows = len(matrix)
 
    for row in range(num_rows):
        # Swap elements at col1 and col2 using a temporary variable
        temp = matrix[row][col1]
        matrix[row][col1] = matrix[row][col2]
        matrix[row][col2] = temp
 
 
def print_matrix(matrix):
    for row in matrix:
        for element in row:
            print(element, end=' ')
        print()
 
 
# Example usage:
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
 
print("Original Matrix:")
print_matrix(matrix)
 
col1 = 0  # Column 1 to swap
col2 = 2  # Column 2 to swap
 
if 0 <= col1 < len(matrix[0]) and 0 <= col2 < len(matrix[0]):
    swap_columns(matrix, col1, col2)
    print("\nMatrix after swapping columns:")
    print_matrix(matrix)
else:
    print("Invalid column indices for swapping.")


C#




using System;
 
public class GFG
{
    public static void SwapColumns(int[,] matrix, int col1, int col2)
    {
        if (col1 == col2)
        {
            return;
          // No need to swap if columns are the same
        }
        int numRows = matrix.GetLength(0);
        for (int row = 0; row < numRows; row++)
        {
            // Swap elements at col1 and col2 using
          // temporary variable
            int temp = matrix[row, col1];
            matrix[row, col1] = matrix[row, col2];
            matrix[row, col2] = temp;
        }
    }
    public static void PrintMatrix(int[,] matrix)
    {
        int numRows = matrix.GetLength(0);
        int numCols = matrix.GetLength(1);
        for (int row = 0; row < numRows; row++)
        {
            for (int col = 0; col < numCols; col++)
            {
                Console.Write(matrix[row, col] + " ");
            }
            Console.WriteLine();
        }
    }
    public static void Main()
    {
        int[,] matrix =
        {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        Console.WriteLine("Original Matrix:");
        PrintMatrix(matrix);
        int col1 = 0; // Column 1 to swap
        int col2 = 2; // Column 2 to swap
        if (col1 >= 0 && col1 < matrix.GetLength(1) && col2 >= 0 && col2 < matrix.GetLength(1))
        {
            SwapColumns(matrix, col1, col2);
            Console.WriteLine("\nMatrix after swapping columns:");
            PrintMatrix(matrix);
        }
        else
        {
            Console.WriteLine("Invalid column indices for swapping.");
        }
    }
}


Javascript




function swapColumns(matrix, col1, col2) {
    if (col1 === col2) {
        return// No need to swap if columns are the same
    }
 
    const numRows = matrix.length;
 
    for (let row = 0; row < numRows; row++) {
        // Swap elements at col1 and col2 using a temporary variable
        const temp = matrix[row][col1];
        matrix[row][col1] = matrix[row][col2];
        matrix[row][col2] = temp;
    }
}
 
function printMatrix(matrix) {
    for (const row of matrix) {
        console.log(row.join(' '));
    }
}
 
// Example usage:
const matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
 
console.log("Original Matrix:");
printMatrix(matrix);
 
const col1 = 0;  // Column 1 to swap
const col2 = 2;  // Column 2 to swap
 
if (col1 >= 0 && col1 < matrix[0].length && col2 >= 0 && col2 < matrix[0].length) {
    swapColumns(matrix, col1, col2);
    console.log("\nMatrix after swapping columns:");
    printMatrix(matrix);
} else {
    console.log("Invalid column indices for swapping.");
}


Output

Original Matrix:
1 2 3 
4 5 6 
7 8 9 

Matrix after swapping columns:
3 2 1 
6 5 4 
9 8 7 




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads