Skip to content
Home » C program to transpose a matrix

C program to transpose a matrix

Below is the code to transpose a matrix

#include <stdio.h>
int main(){
    int c,r;
    printf("Enter number of rows: ");
    scanf("%d",&r);
    printf("Enter number of columns: ");
    scanf("%d",&c);
    int matrix[r][c],matrix2[c][r];
    printf("Enter elements in an array \n");
    int i,j;
    for(i=0;i<r;i++){
        for(j=0;j<c;j++){
            printf("Enter a%d%d ",i+1,j+1);
            scanf("%d",&matrix[i][j]);
        }
    }
    for(i=0;i<r;i++){
        for(j=0;j<c;j++){
            matrix2[j][i]=matrix[i][j];
        }
    }
    printf("Transpose of the given matrix is:\n\n");
    for(i=0;i<c;i++){
        for(j=0;j<r;j++){
            printf("%d      ",matrix2[i][j]);
        }
        printf("\n\n");
    }
}

Output:

Enter number of rows: 2
Enter number of columns: 3
Enter elements in an array
Enter a11 4
Enter a12 6
Enter a13 7
Enter a21 4
Enter a22 2
Enter a23 6
Transpose of the given matrix is:

4 4

6 2

7 6