C Program to Find Transpose of a Matrix using Pointers
C program to find transpose of a matrix : 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
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
- #include<stdio.h>
- #include<stdlib.h>
- int main()
- {
- int matrix[10][10],i,j,r,c;
- printf("\n How many rows and columns in the matrix:- ");
- scanf(" %d %d",&r,&c);
- printf("\n Enter the elements:- ");
- for(i=0;i<r;i++)
- for(j=0;j<c;j++)
- {
- scanf("%d",&matrix[i][j]);
- }
- printf("\n The transpose of matrix is:- \n");
- for(i=0;i<c;i++)
- {
- for(j=0;j<r;j++)
- printf("%5d",matrix[j][i]);
- printf("\n");
- }
- return 0;
- }
- /* Output of above code:-
- How many rows and columns in the matrix:- 3 3
- Enter the elements:-
- 1 2 3
- 4 5 6
- 7 8 9
- The transpose of matrix is:-
- 1 4 7
- 2 5 8
- 3 6 9
- */
Output of C programming code:
C program to find transpose of a matrix using dynamic memory allocation
- #include<stdio.h>
- #include<stdlib.h>
- int main()
- {
- int *transpose,i,j,r,c; //declaring pointers
- printf("\n How many rows and columns in the matrix:- ");
- scanf(" %d %d",&r,&c);
- //allocating memory by using dynamic memory allocation
- transpose=(int*)calloc(r*c,sizeof(int));
- printf("\n Enter the elements:- ");
- for(i=0;i<r;i++)
- for(j=0;j<c;j++)
- {
- scanf("%d",transpose+(i*c+j)*sizeof(int));
- }
- // You can achieve the same result by using pointer concept
- printf("\n The transpose of matrix is:- \n");
- for(i=0;i<c;i++)
- {
- for(j=0;j<r;j++)
- printf("%5d",*(transpose+(j*c+i)*sizeof(int)));
- printf("\n");
- }
- return 0;
- }
- /* Output of above code:-
- How many rows and columns in the matrix:- 3 3
- Enter the elements:-
- 1 2 3
- 4 5 6
- 7 8 9
- The transpose of matrix is:-
- 1 4 7
- 2 5 8
- 3 6 9
- */
Upcoming Programs:
- C program for matrix multiplication