C Program to Find Transpose of a Matrix using Pointers

transpose of a matrix in C : Transpose of a mxn (3x3) matrix can be obtained by interchanging the rows and columns in C using pointers and dynamic memory allocation.

For Example: Consider a 3x3 matrix

1 2 3
4 5 6
7 8 9

Transpose of matrix is
1 4 7
2 5 8
3 6 9

C program to find transpose of a matrix

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. int main()
  4. {
  5. int matrix[10][10],i,j,r,c;
  6. printf("\n How many rows and columns in the matrix:- ");
  7. scanf(" %d %d",&r,&c);
  8. printf("\n Enter the elements:- ");
  9. for(i=0;i<r;i++)
  10. for(j=0;j<c;j++)
  11. {
  12. scanf("%d",&matrix[i][j]);
  13. }
  14. printf("\n The transpose of matrix is:- \n");
  15. for(i=0;i<c;i++)
  16. {
  17. for(j=0;j<r;j++)
  18. printf("%5d",matrix[j][i]);
  19. printf("\n");
  20. }
  21. return 0;
  22. }
  23. /* Output of above code:-
  24. How many rows and columns in the matrix:- 3 3
  25. Enter the elements:-
  26. 1 2 3
  27. 4 5 6
  28. 7 8 9
  29. The transpose of matrix is:-
  30. 1 4 7
  31. 2 5 8
  32. 3 6 9
  33. */

Output of C programming code:

C program to find transpose of a matrix using dynamic memory allocation

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. int main()
  4. {
  5. int *transpose,i,j,r,c; //declaring pointers
  6. printf("\n How many rows and columns in the matrix:- ");
  7. scanf(" %d %d",&r,&c);
  8. //allocating memory by using dynamic memory allocation
  9. transpose=(int*)calloc(r*c,sizeof(int));
  10. printf("\n Enter the elements:- ");
  11. for(i=0;i<r;i++)
  12. for(j=0;j<c;j++)
  13. {
  14. scanf("%d",transpose+(i*c+j)*sizeof(int));
  15. }
  16. // You can achieve the same result by using pointer concept
  17. printf("\n The transpose of matrix is:- \n");
  18. for(i=0;i<c;i++)
  19. {
  20. for(j=0;j<r;j++)
  21. printf("%5d",*(transpose+(j*c+i)*sizeof(int)));
  22. printf("\n");
  23. }
  24. return 0;
  25. }
  26. /* Output of above code:-
  27. How many rows and columns in the matrix:- 3 3
  28. Enter the elements:-
  29. 1 2 3
  30. 4 5 6
  31. 7 8 9
  32. The transpose of matrix is:-
  33. 1 4 7
  34. 2 5 8
  35. 3 6 9
  36. */

Upcoming Programs:

  1. C program for matrix multiplication