Home >>Java Programs >Java Program to determine whether two matrices are equal
In this example, we will create a java program to check whether given matrices are equal or not.
Two matrices are said to be equal if and only if both the matrices have the same number of rows and columns and both the matrices have the same corresponding elements.
public class Main
{
public static void main(String[] args) {
int row1, col1, row2, col2;
boolean flag = true;
int a[][] = {
{1, 7, 3},
{8, 4, 5},
{3, 5, 7}
};
int b[][] = {
{1, 2, 9},
{6, 4, 6},
{4, 5, 5}
};
row1 = a.length;
col1 = a[0].length;
row2 = b.length;
col2 = b[0].length;
if(row1 != row2 || col1 != col2){
System.out.println("Matrices are not equal");
}
else {
for(int i = 0; i < row1; i++){
for(int j = 0; j < col1; j++){
if(a[i][j] != b[i][j]){
flag = false;
break;
}
}
}
if(flag)
System.out.println("Matrices are equal");
else
System.out.println("Matrices are not equal");
}
}
}