C Program to Find Transpose of a Matrix Using Pointers

The transpose of a matrix is a new matrix that has rows equal to the number of columns of the original matrix and columns equal to the number of rows. 

C Program to Find Transpose of a Matrix Using Pointers

The best part of this program is that we will not only display the transpose of the matrix using pointers, but we will also create the matrix itself using pointers. 

Let's create a file named transposemat.c and add the following source code to it:
#include <stdio.h>
#include <stdlib.h>

void main()
{
    int a[10][10],  r, c, i, j, *ptr,m;
    printf("Enter rows and columns of matrix: ");
    scanf("%d %d", &r, &c);
    ptr = (int *)malloc(r * c * sizeof(int)); 
    printf("\nEnter elements of matrix:\n");
    for(i=0; i<r; ++i)
    {
        for(j=0; j<c; ++j)
        {
            scanf("%d", &m);
             *(ptr+ i*c + j)=m;
        }
    }
    printf("\nMatrix using pointer is: \n");
    for(i=0; i<r; ++i)
    {
        for(j=0; j<c; ++j)
        {
           printf("%d\t",   *(ptr +i*c + j));
        }
        printf("\n");
    }
    printf("\nTranspose of Matrix:\n");
    for(i=0; i<c; ++i)
    {
        for(j=0; j<r; ++j)
        {
             printf("%d\t",*(ptr +j*c + i));
        }
        printf("\n");
   }
}

To compile and run the above C program, you can use C Programs Compiler Online tool.

Output:

Enter rows and columns of matrix: 2
3

Enter elements of matrix:
1 2 3
2 4 5 6

Matrix using pointer is: 
1	2	3	
4	5	6	

Transpose of Matrix:
1	4	
2	5	
3	6	



Comments