How can you interchange rows and columns in a two-dimensional array in the C programming language?

One way to swap rows and columns in a two-dimensional array is by creating a new array and placing the original rows as columns in the new array, and the original columns as rows in the new array. The specific steps are as follows:

  1. lines
  2. columns
  3. columns
  4. lines
  5. switch the order of elements in an array
  6. Assign the value of ‘array[i][j]’ to ‘transposeArray[j][i]’.
  7. rearrangeArray

Here is an example code in C language demonstrating the swapping of rows and columns in a two-dimensional array.

#include <stdio.h>

#define MAX_ROWS 3
#define MAX_COLS 3

void transpose(int array[MAX_ROWS][MAX_COLS], int transposeArray[MAX_COLS][MAX_ROWS], int rows, int cols) {
    int i, j;
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            transposeArray[j][i] = array[i][j];
        }
    }
}

int main() {
    int array[MAX_ROWS][MAX_COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int transposeArray[MAX_COLS][MAX_ROWS];
    int rows = MAX_ROWS;
    int cols = MAX_COLS;

    // 调用函数进行行列互换
    transpose(array, transposeArray, rows, cols);

    // 输出互换后的结果
    int i, j;
    for(i = 0; i < cols; i++) {
        for(j = 0; j < rows; j++) {
            printf("%d ", transposeArray[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Running the above code will output the following result:

1 4 7 
2 5 8 
3 6 9 

This is the method for transposing a 2D array.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds