C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Matrix Transpose using pointers

C Program: Matrix Transpose using pointers

C

#include <stdio.h>

 

int main() {

    int a[10][10], transpose[10][10];

    int *p, *t;

    int rows, cols, i, j;

 

    printf("Enter number of rows and columns: ");

    scanf("%d %d", &rows, &cols);

 

    printf("Enter elements of the matrix:\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            scanf("%d", &a[i][j]);

        }

    }

 

    // Initialize pointers

    p = &a[0][0];

    t = &transpose[0][0];

 

    // Find transpose using pointers

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            *(t + j * rows + i) = *(p + i * cols + j);

        }

    }

 

    // Display original matrix

    printf("\nOriginal Matrix:\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            printf("%d ", a[i][j]);

        }

        printf("\n");

    }

 

    // Display transpose

    printf("\nTranspose of the Matrix:\n");

    for (i = 0; i < cols; i++) {

        for (j = 0; j < rows; j++) {

            printf("%d ", transpose[i][j]);

        }

        printf("\n");

    }

 

    return 0;

}

Output

 
OUTPUT :
Enter number of rows and columns: 2 3
Enter elements of the matrix:
1 2 3
4 5 6

Original Matrix:
1 2 3
4 5 6

Transpose of the Matrix:
1 4
2 5
3 6

Explanation

  1. Two matrices a and transpose are declared.
  2. Pointers p and t are assigned to their base addresses.
  3. The formula

                   transpose[j][i]=a[i][j]

is implemented using pointer arithmetic:

*(t + j * rows + i) = *(p + i * cols + j);

  1. The program then prints both the original and the transposed matrix.