Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 33: Write a Java program to perform transpose of a matrix.

Transpose.java

import java.util.Scanner;

public class Transpose
{

	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
			
		System.out.println("Enter the size of the matrix");
		int row=s.nextInt();
		int col=s.nextInt();

		//Input Elements in matrix-1.
		int a[][] = new int[row][col];
		System.out.println("Enter elements of first matrix");

		for(int i=0; i < row; i++)
		{
			for(int j=0; j < col;j++)
			{
				System.out.print("Enter "+i+j+" element: ");
				a[i][j]=s.nextInt();	
			}
		}
	
		//Displaying the original matrix.
		System.out.println("Original matrix");
		for(int i=0; i < row; i++)
		{
			for(int j=0; j < col;j++)
			{
				System.out.print(a[i][j]+" ");
			}
			System.out.println();
		}

		//Displaying the transpose of the matrix.
		System.out.println("Transpose of the matrix");
		for(int i=0; i < row; i++)
		{
			for(int j=0;j < col;j++)
			{
				System.out.print(a[j][i]+" ");
			}
			System.out.println();
		}
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.