Write a Program in C++ & Python to transpose a Matrix

By | October 30, 2021
Write a Program in C++ & Python to transpose a Matrix

Here in this program, we will code to transpose a matrix.

By transposing a matrix means we will change its row with its columns.

E.g.  suppose a matrix

2 3 4

5 6 7

Vamware

8 9 10

The transpose of the upper matrix would be:

Vamware

2 5 8

3 6 7

4 7 10

C++ Program to transpose a Matrix

#include<stdio.h>
#include<conio.h>
#include<iostream.h>
void main()
{
clrscr();
int arr[10][10],r,c;
cout<<"Enter the number of rows: ";
cin>>r;
cout<<"Enter the number of Columns: ";
cin>>c;
cout<<"Enter the matrix element:\n";
for(int i=0;i<c;i++)
    for(int j=0; j<r; j++)
                cin>>arr[i][j];
cout<<"The transpose of the matrix would be\n";
for(i=0;i<c;i++)
   {
   for(j=0;j<r;j++)
      cout<<arr[j][i]<<" ";
   cout<<endl;
   }
getch();
}

Output:

Enter the number of rows: 2
Enter the number id Columns: 3
Enter the matrix elements

1
2
3
4
5
6

The transpose of the matrix would be

1 4
2 5
3 6

Python to Transpose a Matrix:

a=[]
arr =[]
r= int(input("Enter the number of rows: "))
c= int(input("Enter the number id Columns: "))
print("Enter the matrix elements")
for i in range(r):         
    a =[]
    for j in range(c):     
        a.append(int(input()))
    arr.append(a)
print("The transpose of the matrix would be")
for i in range(c):
    for j in range(r):
        print(arr[j][i],end=" ")
    print()

Output:

Enter the number of rows: 3
Enter the number id Columns: 3
Enter the matrix elements

12
23
12
34
45
65
47
23
877

The transpose of the matrix would be

12 34 47
23 45 23
12 65 877

People are also reading:

Author: Vinay

I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

Leave a Reply

Your email address will not be published.