C program to interchange the rows in the matrix

Here, we are going to learn how to interchange the rows in the matrix in C programming language?
Submitted by Nidhi, on July 13, 2021

Problem Solution:

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.

C Two-dimensional Arrays Programs »





Comments and Discussions!

Load comments ↻





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