Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Array

2D Array

Patterns

Excersises


C Program to Find Transpose of a Matrix


Here’s a C program to find the transpose of a matrix. The transpose of an 𝑀 Γ— 𝑁 matrix becomes an 𝑁 Γ— 𝑀 matrix. The program dynamically calculates the transpose based on user input for dimensions.

Example : transpose_of_2darray.c
#include <stdio.h>

int main() {
  int rows, cols;

  // Input dimensions of the matrix
  printf("Enter the number of rows: ");
  scanf("%d", &rows);
  printf("Enter the number of columns: ");
  scanf("%d", &cols);

  int matrix[rows][cols], transpose[cols][rows];

  // Input elements of the matrix
  printf("Enter the elements of the matrix:\n");
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("Enter element at [%d][%d]: ", i, j);
      scanf("%d", &matrix[i][j]);
    }
  }

  // Calculate the transpose
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      transpose[j][i] = matrix[i][j];
    }
  }

  // Display the original matrix
  printf("\nOriginal Matrix:\n");
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("%d ", matrix[i][j]);
    }
    printf("\n");
  }

  // Display the transpose matrix
  printf("\nTranspose of the Matrix:\n");
  for (int i = 0; i < cols; i++) {
    for (int j = 0; j < rows; j++) {
      printf("%d ", transpose[i][j]);
    }
    printf("\n");
  }

  return 0;
}

Output:

Enter the number of rows: 2
Enter the number of columns: 2
Enter the elements of the matrix:
Enter element at [0][0]: 1
Enter element at [0][1]: 2
Enter element at [1][0]: 3
Enter element at [1][1]: 4

Original Matrix:
1 2
3 4

Transpose of the Matrix:
1 3
2 4