C Program to Compute Transpose of a Matrix

Introduction

This example will show you how to compute transpose of a matrix in C program. In this example a user will be asked to enter the number of rows and columns for matrices. Then user will be asked to enter the elements at each index of the matrix. A matrix has to be square matrix for computing the transpose of that matrix.

Here we will see also how to use pointers to allocate memory dynamically for array using malloc function.

Transpose of an N x N (row x column) square matrix A is a matrix B such that an element bi,j of B is equal to the element of aj,i of A for 0<=i,j<N.

C Program

The following C program computes the transpose of the given matrix.

/* 
 * File:   matrixTranspose.c
 * Author: https://roytuts.com
 *
 */

#include <stdio.h>
#include <stdlib.h>

void matrixTranspose(int **a, int r, int c) {
    int i, j, temp;

    for (i = 0; i < r; i++) {
        for (j = i + 1; j < c; j++) {
            temp = a[i][j];
            a[i][j] = a[j][i];
            a[j][i] = temp;
        }
    }
}

int main() {

    int i, j, rows, cols, **a;

    printf("Transpose of a Matrix");

    printf("\nEnter number of rows :");
    scanf("%d", &rows);
    printf("\nEnter number of columns :");
    scanf("%d", &cols);

    // allocate rows, each row is a pointer to int
    a = malloc(rows * sizeof (int *));

    // for each row allocate cols int
    for (i = 0; i < rows; i++) {
        a[i] = malloc(cols * sizeof (int));
    }

    printf("\nEnter Matrix\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            printf("Enter Element %d %d : ", i, j);
            scanf("%d", &a[i][j]);
        }
    }

    matrixTranspose(a, rows, cols);

    printf("\nTranspose of the given Matrix\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < rows; j++) {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output

Running the above program will produce below output:

Transpose of a Matrix
Enter number of rows :3

Enter number of columns :3

Enter Matrix
Enter Element 0 0 : 1
Enter Element 0 1 : 2
Enter Element 0 2 : 3
Enter Element 1 0 : 4
Enter Element 1 1 : 5
Enter Element 1 2 : 6
Enter Element 2 0 : 7
Enter Element 2 1 : 8
Enter Element 2 2 : 9

Transpose of the given Matrix
1 4 7 
2 5 8 
3 6 9

Source Code

download source code

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *