How to swap two rows of elements in a matrix using C language arrays?

To swap two rows of a matrix, you need to iterate through each column and exchange the corresponding elements of the two rows. Here is an example code:

#include <stdio.h>

#define ROWS 3
#define COLS 3

// 交换矩阵的两行元素
void swapRows(int matrix[ROWS][COLS], int row1, int row2) {
    for (int col = 0; col < COLS; col++) {
        // 交换两行对应位置的元素
        int temp = matrix[row1][col];
        matrix[row1][col] = matrix[row2][col];
        matrix[row2][col] = temp;
    }
}

int main() {
    int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int row1 = 0;
    int row2 = 1;

    // 交换矩阵的两行元素
    swapRows(matrix, row1, row2);

    // 打印交换后的矩阵
    for (int row = 0; row < ROWS; row++) {
        for (int col = 0; col < COLS; col++) {
            printf("%d ", matrix[row][col]);
        }
        printf("\n");
    }

    return 0;
}

In this code snippet, a swapRows function is first defined, which accepts a 2D array matrix and two row indices, row1 and row2. Within the function, a loop is used to iterate through each column of the matrix and swap the elements at corresponding positions in the two rows. Then in the main function, an array matrix and row indices row1 and row2 are defined, and the swapRows function is called to swap the elements of the two rows in the matrix. Finally, nested loops are used to print the swapped matrix. Running this code will output the swapped matrix.

4 5 6 
1 2 3 
7 8 9 
bannerAds