Transposing A Matrix Using C.

Hey there developer friends, today I will be showing you how to transpose a matrix using C.

From the last article on Adding 2D Arrays in C, here we will just see how to transpose the matrix.

So with that said, let's get started.

#include <stdio.h>

int main(void) {
    // first thing to do is to declare two arrays. One for the input and one for the transpose
   int arr[2][2];

   int transpose[2][2];
   printf("Enter values for the matrix\n");

   for(int i = 0; i < 2; i++){
       for(int j = 0; j < 2; j++){
// Don't forget, since we're dealing with a 2D array, we have to use a nested loop(it's basically a loop nested in a loop.
           printf("Enter arr[%d][%d] = ",i,j);
           scanf("%d",&arr[i][j]);
       }

   }

   for(int i = 0; i < 2; i++){
       for(int j = 0; j < 2; j++){
// here, just like in maths this is where the transpose happens
           transpose[j][i] = arr[i][j];  
       }

   }
   for(int i = 0; i <2; i++){
       for(int j = 0; j < 2; j++){
              printf("%d \t" , transpose[i][j]);
       }
    printf("\n");
   }
    return 0;
}

As always guys, make sure to check the comments in the code, it'll explain what each line is for. I didn't quite explain everything in detail because I already did that in the last article.

So if you've not read that, make sure to go back and check it out. And guys to read my articles right in your emails. Subscribe to my email list and we'll see how it goes.

Until next time.

Peace.