Program to Transpose Matrix In-place in C

Write a Program To Transpose Matrix In-Place in C.

In-place means we will not use a separate array for the output Matrix. We will modify the input array.

Example,

Input
1 2 3
4 5 6
7 8 9
Output
1 4 7
2 5 8
3 6 9

Input
1 2 3 4
5 6 7 8
Output
1 5
2 6
3 7
4 8

The Transpose of a Matrix means a new Matrix in which the rows are the columns ( or the columns are the rows ) of the original Matrix.

The user first enters the number of rows and number of columns of the Matrix.

After that, the program asks user to enter the Matrix row-wise.

Algorithm To Transpose Matrix In-place

To Transpose Matrix, we need to swap all Matrix[row][column] and Matrix[column][row] pairs once.

The following illustration shows how the algorithm works,

transpose matrix inpalce in c

Program to Transpose Matrix In-place in C

The Program will work for both rectangular and square matrices.

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

int main() {
	int i, j, temp;
	int r, c;
	int matrix[50][50];

	printf("Enter Number of Rows in Matrix: ");
	scanf("%d", &r);
	printf("Enter Number of columns in Matrix: ");
	scanf("%d", &c);

	printf("Enter Matrix: \n");
	for (i = 0; i < r; ++i) {
		for (j = 0; j < c; ++j) {
			scanf("%d", &matrix[i][j]);
		}
	}
	
	// Transposing Matrix
	for (i = 0; i < r; ++i) {
		for (j = i; j < c; ++j) {
			temp = matrix[i][j];
			matrix[i][j] = matrix[j][i];
			matrix[j][i] = temp;
		}
	}
	
	printf("Transpose of Matrix: \n");
	for (i = 0; i < c; ++i) {
		for (j = 0; j < r; ++j) {
			printf("%d ",matrix[i][j]);
		}
		printf("\n");
	}
	
}

Output

program transpose matrix in place c/c++

What to Study Next?

  1. Program for Matrix Multiplication
  2. Program to Transpose Matrix

References

Transpose Matrix Inplace

Leave a Comment

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