Python/C/C++/JAVA

Moderate Practice Programs with Code and Concept

By D.S

Transpose of a Matrix

When dealing with matrices, sometimes it becomes necessary to change the rows and columns of a matrix. This process is known as transposing the matrix. Luckily for us, there are many programming languages that make it easy to transpose matrices. In C++, we can simply use nested loops to loop through each element in the matrix and swap them based on their positions. Similarly, in Python, we can use the built-in numpy library to transpose matrices using just one line of code. Java also has tools available such as its Matrix class from its math package which includes an in-built transpose method. Ultimately, regardless of what language you're working in, take advantage of helpful methods and libraries available so that you don't have to reinvent the wheel when it comes time to transpose a matrix!

(a.) C Code

#include <stdio.h>

int main() {
    int rows, cols;

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

    int matrix[rows][cols];
    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 position (%d, %d): ", i + 1, j + 1);
            scanf("%d", &matrix[i][j]);
        }
    }

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

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

    return 0;
}
Output:-
Enter the number of rows: 3
Enter the number of columns: 2
Enter the elements of the matrix:
Enter element at position (1, 1): 1
Enter element at position (1, 2): 2
Enter element at position (2, 1): 3
Enter element at position (2, 2): 4
Enter element at position (3, 1): 5
Enter element at position (3, 2): 6

Original Matrix:
1 2
3 4
5 6
Transpose of the Matrix:
1 3 5
2 4 6

(b.) C++ Code

#include <iostream>
      using namespace std;
      
      int main() {
          int rows, cols;
      
          cout << "Enter the number of rows: ";
          cin >> rows;
          cout << "Enter the number of columns: ";
          cin >> cols;
      
          int matrix[rows][cols];
          cout << "Enter the elements of the matrix:\n";
          for (int i = 0; i < rows; ++i) {
              for (int j = 0; j < cols; ++j) {
                  cout << "Enter element at position (" << i + 1 << ", " << j + 1 << "): ";
                  cin >> matrix[i][j];
              }
          }
      
          cout << "\nOriginal Matrix:\n";
          for (int i = 0; i < rows; ++i) {
              for (int j = 0; j < cols; ++j) {
                  cout << matrix[i][j] << "\t";
              }
              cout << "\n";
          }
      
          cout << "\nTranspose of the Matrix:\n";
          for (int i = 0; i < cols; ++i) {
              for (int j = 0; j < rows; ++j) {
                  cout << matrix[j][i] << "\t";
              }
              cout << "\n";
          }
      
          return 0;
      }
Output:-
Enter the number of rows: 3
Enter the number of columns: 2
Enter the elements of the matrix:
Enter element at position (1, 1): 1
Enter element at position (1, 2): 2
Enter element at position (2, 1): 3
Enter element at position (2, 2): 4
Enter element at position (3, 1): 5
Enter element at position (3, 2): 6

Original Matrix:
1 2
3 4
5 6
Transpose of the Matrix:
1 3 5
2 4 6

(c.) Python Code

def main():
      rows = int(input("Enter the number of rows: "))
      cols = int(input("Enter the number of columns: "))
  
      matrix = []
      print("Enter the elements of the matrix:")
      for i in range(rows):
          row = []
          for j in range(cols):
              element = int(input(f"Enter element at position ({i + 1}, {j + 1}): "))
              row.append(element)
          matrix.append(row)
  
      print("\nOriginal Matrix:")
      for i in range(rows):
          for j in range(cols):
              print(matrix[i][j], end="	")
          print()
  
      print("\nTranspose of the Matrix:")
      for i in range(cols):
          for j in range(rows):
              print(matrix[j][i], end="	")
          print()
  
  if __name__ == "__main__":
      main()
Output:-
Enter the number of rows: 3
Enter the number of columns: 2
Enter the elements of the matrix:
Enter element at position (1, 1): 1
Enter element at position (1, 2): 2
Enter element at position (2, 1): 3
Enter element at position (2, 2): 4
Enter element at position (3, 1): 5
Enter element at position (3, 2): 6

Original Matrix:
1 2
3 4
5 6
Transpose of the Matrix:
1 3 5
2 4 6

(d.) Java Code

(d.) Java Code

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int rows = scanner.nextInt();
        System.out.print("Enter the number of columns: ");
        int cols = scanner.nextInt();

        int[][] matrix = new int[rows][cols];
        System.out.println("Enter the elements of the matrix:");
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                System.out.print("Enter element at position (" + (i + 1) + ", " + (j + 1) + "): ");
                matrix[i][j] = scanner.nextInt();
            }
        }

        System.out.println("\nOriginal Matrix:");
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
        }

        System.out.println("\nTranspose of the Matrix:");
        for (int i = 0; i < cols; ++i) {
            for (int j = 0; j < rows; ++j) {
                System.out.print(matrix[j][i] + "\t");
            }
            System.out.println();
        }
    }
}
Output:-
Enter the number of rows: 3
Enter the number of columns: 2
Enter the elements of the matrix:
Enter element at position (1, 1): 1
Enter element at position (1, 2): 2
Enter element at position (2, 1): 3
Enter element at position (2, 2): 4
Enter element at position (3, 1): 5
Enter element at position (3, 2): 6

Original Matrix:
1 2
3 4
5 6
Transpose of the Matrix:
1 3 5
2 4 6