Two matrices are said to be equal if they have same number of rows and columns and their corresponding elements are equal.
Example:
| 4 | 5 | 3 |
| 2 | 8 | 7 |
| 1 | 9 | 0 |
| 4 | 5 | 3 |
| 2 | 8 | 7 |
| 1 | 9 | 0 |
Here both matrices have same dimensions and their corresponding elements are also same.
Define a class with following specification to check the above.
Class Name: EqMatrix
Member Variables:
ar[][] – Integer matrix.
row – Store the number of rows of a matrix.
col – Store the number of columns of a matrix.
Member Methods:
EqMatrix() – Default constructor to initialize member variables.
void getInput() – Accept the size of matrix and elements in the matrix.
String isEqual(EqMatrix A,EqMatrix B) –
To check and return proper statement whether the two matrices are equal or not.
Invoke all the above methods in main() function using object of the class. Use a separate object to invoke isEqual(EqMatrix A,EqMatrix B) function.
import java.util.*;
public class EqMatrix
{
int ar[][];int row;int col;
EqMatrix()
{
row=0;
col=0;
}
public void getInput()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter no.of rows: ");
row=sc.nextInt();
System.out.print("Enter no.of columns: ");
col=sc.nextInt();
ar=new int[row][col];
System.out.println("Enter matrix elements:-");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
ar[i][j]=sc.nextInt();
}
}
}
public String isEqual(EqMatrix A,EqMatrix B)
{
if(A.row!=B.row||A.col!=B.col)
{
return "Not equal matrix";
}
for(int i=0;i<A.row;i++)
{
for(int j=0;j<A.col;j++)
{
if(A.ar[i][j]!=B.ar[i][j])
{
return "Not equal matrix";
}
}
}
return "Equal matrix";
}
public static void main(String args[])
{
EqMatrix ob1=new EqMatrix();
EqMatrix ob2=new EqMatrix();
EqMatrix ob3=new EqMatrix();
ob1.getInput();
ob2.getInput();
System.out.println(ob3.isEqual(ob1,ob2));
}
}Java