Find the transpose of a matrix in C-Programming:
First of all we have to know what is the definition of the transpose of a matrix. For a matrix A, we define the transpose of A by AT interchanging the elements of corresponding row and column of A. More easily we have to swap the 1st row with the 1st column and 2nd row with the 2nd column and so on. So here we find the transpose of a matrix in C-Programming.
Transpose of Matrix |
Important:
1. for-loop2. use of array
You can also see:
Representation of a matrixSum of two matrix
Code:
#include<stdio.h>
int main()
{
int n,m,i,j,a[20][20];
printf("Enter the order of the matrix:");
scanf("%d%d",&n,&m);
printf("Enter the element of the matrix row wise:");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
scanf("%d",&a[i][j]);
}
printf("The given matrix is:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d \t",a[i][j]);
}
printf("\n");
}
printf("The transpose of the given matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d \t",a[j][i]);
}
printf("\n");
}
}
Output:
The output is:
Explanation:
1. First we used the header package <stdio.h>. Visit Header package to know more.
2. We include the integer variables n,m,i,j and a[20][20]. First we used n for store how many row and m for how many column. i and j have been used for for-loop. a[20][20] has been used to store the element of the matrix. Here we use int a[20][20] for store only the integer element in the matrix, you can use float a[20][20] for store the real number.
3. Then we store the order of the matrix in n and m with scanf.
4. Then we store all the elements of the matrix using for-loop row wise.
5. After that we display the matrix using for-loop by printf syntax.
6. Next we display the transpose of the matrix.
Lets see with an example how the first for-loop works-
The loops is like this:
for(i=0;i<n;i++)Suppose that user want to type a 3x2 matrix. So n=3 and m=2, now 1st for-loop start from i=0 which less than 3 so it will go into 2nd for loop and start with j=0 which is less than 2 so it will enter in the bracket of 2nd for-loop and scan the number and store it in 00 position. Now it will leave from the bracket and increased by 1 so j will be now 1 and which is less than 2 so it again enter into the 2nd for-loop and doing the same process and it will store the number in the 01 position and exit and increasing j with 1. Now j will be 2 which is not less that 2 therefore it will not entered in the 2nd for-loop. It will again enter 1st for-loop for i=1 and doing the same process and exit and will increase the value of i that is, it will be 2 which is less than 3 and it will enter in the 1st for-loop and doing the same process. It will running till the condition is satisfied.
{
for(j=0;j<m;j++)
scanf("%d",&a[i][j]);
}
No comments:
Post a Comment