InterviewSolution
| 1. |
Two matrices are said to be equal if they have the same dimension and their corresponding elements are equal.For example, the two matrices A and B is given below are equal:Matrix A123145356Matrix B123245356Design a class EqMat to check if two matrices are equal or not. Assume that the two matrices have the same dimension. Some of the members of the class are given below : Class name: EqMat Data members/instance variables: a[][] : to store integer elements m: to store the number of rows n: to store the number of columns Member functions/methods: EqMat: parameterized constructor to initialise the data members m = mm and n = nn void readArray(): to enter elements in the array int check(EqMat P, EqMat Q): checks if the parameterized objects P and Q are equal and returns 1 if true, otherwise returns 0 void print(): displays the array elements Define the class EqMat giving details of the constructor ), void readarray( ), int check(EqMat, EqMat) and void print( ). Define the main( ) function to create objects and call the functions accordingly to enable the task. |
|
Answer» import java.io.*; import java.util.Scanner; class EqMat{ private int a[][]; private static int m; private static int n; public EqMat(int mm, int nn) { m = mm; n = nn; a = newint[m][n]; } public void readArray( )throws IOException { Scanner sc = new Scanner(System.in); for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { a[i][j] = sc.nextInt(); } } } public static boolean check(EqMat p, EqMat q) { boolean flag = true; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(p.a[i][j] !=q.a[i][j]) return false; } } return flag; } public void print() { for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { System.out.print(a[i] [j] + “\t”); } System.out.println(); } } public static void main(String args[ ]) throws IOException { Scanner sc = new Scanner(System.in); System.out.print(“Number of rows: ”); int rows = sc.nextInt(); System.out.print(“Number of columns: ”); int columns = sc.nextInt(); EqMat obj 1 = new EqMat(rows, columns); EqMat obj2 = new EqMat(rows, columns); System.out.println(“Enter elements for first matrix:”); obj1.readArray(); System.out.println(“Enter elements for second matrix:”); obj2.readArray(); System. out.println(“First Matrix:”); obj1.print(); System.out.println(“Second Matrix:”); obj2.print(); if(check(obj1, obj2)) System.out.println(“Both Matrices are Equal”); else System.out.println(“Matrices are not Equal”); } } |
|