Search code examples
javaarraysfor-loop2dvariable-length-array

Write a program that checks if a 2-D integer array is a square array, meaning, if its rows and columns are equal. My code is below


package Homeworks;

public class HomeWork85 {
public static void main(String[] args) {


    int[][] a = {
            {1,1,1,2},
            {1,1,1},
            {1,1,1}
        };

    int[][] b = {
            {1,1,1,1},
            {1,1,1,1},
            {1,1,1,1}
        };

    for (int i=0; i<a.length;i++) {
        for (int j=0;j<a[i].length-1;j++) {
            if (a.length==a[j].length) {
                System.out.println("It is a square");
            }else {
                System.out.println("Not a square");
            }
        }
    }
}
}

Solution

  • Although your logic is correct, you are doing redundant checking. What you should ideally do is you have the row length using a.length. You should iterate through each row once, using a[j].length and check whether the number of rows is equal to the number of values in each row(number of columns).

    If not, then print 'not a square' and break out of the loop. Keep a flag indicating that the loop was stopped explicitly. If not, the flag remains the same and you can conclude that it was a square.

    int flag = 0;
    for (int j=0;j<a.length;j++) {
    
            if (a.length != a[j].length){
                System.out.println("Not a Square!");
                flag = 1;
                break;
            }
    
    }   
    if (flag == 0){
        System.out.println("It is a Square");
    }