TopMagic squaresUsing for loops to check magic squares

Using for loops to check magic squares

Suppose we are given a two-dimensional array of int values

   int[][] magicIntArray = new int[SIZE][SIZE];

that has been filled with values, and we want to determine if it is a magic square.

We need to verify that the sum of each row, each column, and each diagonal, are the same. We begin by computing the sum of the first row, so we can compare it to other sums we compute.

    int firstSum = 0;

    for (col = 0; col < SIZE; col++) {
       firstSum = firstSum + magicIntArray[row][col];
    }
    System.out.println ("The sum in the first row = " + firstSum);

Next, we compute the sums of the other rows and make sure they match the first. We print a message if the sum is different than what we expect, and set a boolean flag to false, indicating that we have determined that the array is not a valid magic square:

  for (int row = 1; row < SIZE; row++) {  // check sum of each row
    sum = 0;
    for (col = 0; col < SIZE; col++) {
      sum = sum + magicIntArray[row][col];
    }
    if (sum != firstSum) {
      System.out.println("The sum of elements in row "+row+" is "+ sum);
      isMagicSquare = false;
    }
  }

Now, the columns. We need to do our loops in the opposite nesting order.

   for (col = 0; col < SIZE; col++) {      // check sum of each column
      sum = 0;
      for (row = 0; row < SIZE; row++) {
        sum = sum + magicIntArray[row][col];
      }
      if (sum != firstSum) {
        System.out.println("The sum of elements in column "+col+" is "+ sum);
        isMagicSquare = false;
      }
   }

TopMagic squaresUsing for loops to check magic squares