Hello I am trying to understand the code I have written and why does it print the output below
public void isSymmetricNow(int[][] matrix){
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[i][j] != matrix[j][i]) {
System.out.print("matrix is not symmetric \n");
}
}
}
System.out.print("matrix is symmetric \n");
}
prints me
matrix is not symmetric
matrix is not symmetric
matrix is symmetric
ASSUME THAT the given matrix is not symmetric here.
int matrix3[][] = {{1,4,7},{-4,6,6},{7,6,9}};
How can I modify this code to give me back saying if the matrix is symmetric or not only once.
Just a plain return statement will do. It will not execute again if the condition is false.
public void isSymmetricNow(int[][] matrix){
//Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
System.out.print("matrix is not symmetric \n");
return;
}
}
}
System.out.print("matrix is symmetric \n");
}
Or
You could return a boolean saying it is a Symmetric or not.
public boolean isSymmetricNow(int[][] matrix){
//Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
//matrix[i][j] = random.nextInt(20);
if (matrix[i][j] != matrix[j][i]) {
return false;
}
}
}
return true;
}
then call it using your function.
if(isSymmetric(matrix))
System.out.println("Symmetric");
else
System.out.println("Not Symmetric");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With