Q:

C program to interchange the rows in the matrix

0

C program to interchange the rows in the matrix

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Given a matrix, and we have to interchange the specified rows in the matrix using C program.

Program:

The source code to interchange the rows in the matrix is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to interchange the rows in matrix

#include <stdio.h>

int main()
{
    int Matrix[3][3] = {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };

    int i, j, n1, n2, temp;

    printf("Matrix before row exchange:\n");
    for (i = 0; i < 3; ++i) {
        for (j = 0; j < 3; ++j)
            printf(" %d", Matrix[i][j]);
        printf("\n");
    }

    printf("Enter two row numbers to be exchanged:");
    scanf("%d %d", &n1, &n2);

    //Exchange rows
    for (i = 0; i < 3; ++i) {
        temp = Matrix[n1 - 1][i];

        Matrix[n1 - 1][i] = Matrix[n2 - 1][i];
        Matrix[n2 - 1][i] = temp;
    }

    printf("Matrix after row exchange:\n");
    for (i = 0; i < 3; ++i) {
        for (j = 0; j < 3; ++j)
            printf(" %d", Matrix[i][j]);
        printf("\n");
    }

    return 0;
}

Output:

RUN 1:
Matrix before row exchange:
 1 2 3
 4 5 6
 7 8 9
Enter two row numbers to be exchanged:1 3
Matrix after row exchange:
 7 8 9
 4 5 6
 1 2 3

RUN 2:
Matrix before row exchange:
 1 2 3
 4 5 6
 7 8 9
Enter two row numbers to be exchanged:1 2
Matrix after row exchange:
 4 5 6
 1 2 3
 7 8 9

RUN 3:
Matrix before row exchange:
 1 2 3
 4 5 6
 7 8 9
Enter two row numbers to be exchanged:2 3
Matrix after row exchange:
 1 2 3
 7 8 9
 4 5 6

Explanation:

In the main() function, we created a 3X3 matrix matrix using the 2D array. Then we read row numbers to be exchanged. After that, we interchanged the rows and printed the updated matrix on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to interchange the columns in the matrix... >>
<< C program to check a given matrix is a sparse matr...