C Language | Swap Elements of 2D Array Rows and Columns

“To become a master, it’s not something that can be achieved overnight, unless you’re a natural talent in martial arts, but such people… are one in a million.”
—— Landlady
This principle also applies to learning C language. After all, those with exceptional programming talent are few and far between. Most of us need to progress from being a C language novice to a master through consistent daily practice.
So how do we learn? Of course, by practicing a C language problem every day!!

C Language | Swap Elements of 2D Array Rows and Columns

Author

Yan Xiaolin

Working during the day and dreaming at night. I have stories, do you have any wine?

Example 24: Implementing the swapping of elements in the rows and columns of a two-dimensional array in C language, storing the result in another two-dimensional array.
For example:
Array a sequence:
     1 2 3
     4 5 6
Array b sequence:
     1 4
     2 5
     3 6
Problem-solving approach: We can define two arrays: Array a with 2 rows and 3 columns to store 6 specified numbers. Array b with 3 rows and 2 columns, initially unassigned, will store the elements from array a at b[j][i].
Source code demonstration:
#include<stdio.h>// Header file 
int main()// Main function 
{
  int i,j;// Define integer variables 
  int a[2][3]={{1,2,3},{4,5,6}};// Define a two-dimensional array and assign initial values 
  int b[3][2];// Define another two-dimensional array
  printf("Horizontal array sequence:\n");// Prompt statement 
  for(i=0;i<2;i++)// Outer for loop, limiting rows, total 2 rows 
  {
    for(j=0;j<3;j++)// Inner for loop, limiting columns, total 3 columns 
    {
      printf("%6d",a[i][j]);// Output array element value, width 6 
      b[j][i]=a[i][j];// Assign value 
    }
  printf("\n");// New line 
  }
  
  printf("Vertical array sequence:\n");// Prompt statement 
  for(i=0;i<3;i++)// Outer for loop, limiting rows, total 3 rows 
  {
    for(j=0;j<2;j++)// Inner for loop, limiting columns, total 2 columns 
    {
      printf("%6d",b[i][j]);// Output array element value, width 6 
    }
  printf("\n");// New line
  }
  return 0;// Function return value is 0 
}
The compilation and execution results are as follows:
Horizontal array sequence:
     1     2     3
     4     5     6
Vertical array sequence:
     1     4
     2     5
     3     6

--------------------------------
Process exited after 0.04857 seconds with return value 0
Press any key to continue...
If you found this helpful, please give Xiaolin a thumbs up and share it with those around you. This will motivate Xiaolin to keep updating. Thank you very much to all the folks!

Follow the official account below, reply with 1, and you’ll be added for free to a programming community of 15,000 people, plus receive 100 C language source code cases, including Snake, Tetris, heart-shaped confession, and Christmas tree source code~

Click to follow and quickly get started with C language

Leave a Comment