# Program to change the given matrix to transpose of the matrix.

21 April 2023

21 April 2023

Write a program to change the given matrix to transpose of the matrix.

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

## Description

Given an N x N matrix, write a program to change the given matrix to transpose of the matrix.

NB: Try without an extra matrix.

Sample input :

3

1 2 3

4 5 6

7 8 9

Sample output:

1 4 7

2 5 8

3 6 9

## C Program

#include <stdio.h>

int main()

{

int n;

scanf("%d",&n);

int mat[n][n];

for(int i = 0 ; i<n ; i++){

for(int j = 0 ; j<n ; j++){

scanf("%d",&mat[i][j]) ;

}

}

int temp;

for(int i = 0 ; i<n ; i++){

for(int j = 0 ; j<(n/2) ; j++){

temp = mat[i][j];

mat[i][j] = mat[j][i];

mat[j][i] = temp;

}

}

for(int i = 0 ; i<n ; i++){

for(int j = 0 ; j<n ; j++){

printf("%d ",mat[i][j]) ;

}

printf("\n");

}

return 0;

}

## C++ Program

#include <bits/stdc++.h>

using namespace std;

int main()

{

int n;

cin>>n;

int mat[n][n];

for(int i = 0 ; i<n ; i++){

for(int j = 0 ; j<n ; j++){

cin>>mat[i][j];

}

}

int temp;

for(int i = 0 ; i<n ; i++){

for(int j = 0 ; j<(n/2) ; j++){

temp = mat[i][j];

mat[i][j] = mat[j][i];

mat[j][i] = temp;

}

}

for(int i = 0 ; i<n ; i++){

for(int j = 0 ; j<n ; j++){

cout<<mat[i][j]<<" ";

}

cout<<"\n";

}

return 0;

}

## JAVA Program

import java.util.*;

import java.lang.*;

import java.io.*;

class Main

{

public static void main (String[] args) throws java.lang.Exception

{

Scanner sc=new Scanner(System.in);

int n = sc.nextInt();

int mat[][] = new int[n][n];

for(int i = 0 ; i<n ; i++){

for(int j = 0 ; j<n ; j++){

mat[i][j] = sc.nextInt();

}

}

int temp;

for(int i = 0 ; i<n ; i++){

for(int j = 0 ; j<(n/2) ; j++){

temp = mat[i][j];

mat[i][j] = mat[j][i];

mat[j][i] = temp;

}

}

for(int i = 0 ; i<n ; i++){

for(int j = 0 ; j<n ; j++){

System.out.print(mat[i][j] + " ");

}

System.out.println();

}

}

}

## PYTHON Program

m = [[1,2,3],[4,5,6],[7,8,9]]

rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]

for row in rez:

print(row)

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023