C# program to interchange the columns of the matrix

Here, we are going to learn how to interchange the columns of the matrix in C#?
Submitted by Nidhi, on November 05, 2020 [Last updated : March 19, 2023]

Interchanging Matrix's Columns

Here, we read a matrix and then read the column numbers to be swapped, and swap the columns, and print the matrix after interchanging columns.

C# code for interchanging matrix's columns

The source code to interchange the columns of the matrix is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to interchange the columns of the matrix.

using System;

class MatrixDemo
{
    public static void Main(string[] args)
    {
        int i   = 0;
        int j   = 0;

        int row = 3;
        int col = 3;

        int col1 = 0;
        int col2 = 0;

        int[,] Matrix = new int[row, col];
        
        Console.Write("Enter the elements of matrix: ");
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < col; j++)
            {
                Matrix[i, j] = int.Parse(Console.ReadLine());
            }
        }

        Console.WriteLine("\nMatrix before swapping: ");
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < col; j++)
            {
                Console.Write(Matrix[i, j] + "\t");
            }
            Console.WriteLine();
        }

        Console.WriteLine("Enter the column Numbers to interchange: ");
        col1 = Convert.ToInt32(Console.ReadLine());
        col2 = Convert.ToInt32(Console.ReadLine());

        for (int k = 0; k < row; k++)
        {
            int temp = Matrix[k, col1 - 1];
            Matrix[k, col1 - 1] = Matrix[k, col2 - 1];
            Matrix[k, col2 - 1] = temp;
        }

        Console.WriteLine("\nMatrix After swapping: ");
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < col; j++)
            {
                Console.Write(Matrix[i, j] + "\t");
            }
            Console.WriteLine();
        }
    }
}

Output

Enter the elements of matrix: 1
2
3
4
5
6
7
8
9

Matrix before swapping:
1       2       3
4       5       6
7       8       9
Enter the column Numbers to interchange:
1
2

Matrix After swapping:
2       1       3
5       4       6
8       7       9
Press any key to continue . . .

Explanation

In the above program, we created a class MatrixDemo that contains the Main() method. Here, we read a 3X3 matrix and then read the column numbers to interchange then we swapped the columns of the matrix using the below code.

for (int k = 0; k < row; k++)
{
    int temp = Matrix[k, col1 - 1];
    Matrix[k, col1 - 1] = Matrix[k, col2 - 1];
    Matrix[k, col2 - 1] = temp;
}

After that, we printed the matrix after interchanging columns.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.