Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Exercise 17

1. Write a class to create a m x n matrix and a method to find out its transpose
without using another array. demonstrate the operation in an
application(main) class.
Ans.
import java.util.*;

class matrix

int row,col;

int a[][];

matrix(int m, int n)

row = m;

col = n;

a = new int[m][n];

void input()

Scanner sc = new Scanner(System.in);

int i,j;

for(i=0;i<row;i++)

System.out.println("Insert row "+(i+1));

for(j=0;j<col;j++)

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

void display()

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

for(int j=0;j<col;j++)

System.out.print(a[i][j]+"\t");

System.out.println("");

void Transpose()

int i,j,temp;

for(i=0;i<row;i++)

for(j=0;j<col;j++)

if(i<j)

temp = a[i][j];

a[i][j] = a[j][i];

a[j][i] = temp;

class Ex17

public static void main(String args[])

Scanner sc = new Scanner(System.in);


int r,c;

System.out.println("Enter the number of rows and colums :");

r = sc.nextInt();

c = sc.nextInt();

matrix obj= new matrix(r,c);

System.out.println("Enter the elemets of matrix:");

obj.input();

System.out.println("Matrix is:");

obj.display();

System.out.println("Transpose of given matrix is:");

obj.Transpose();

obj.display();

You might also like