Kiran Gokal
Kiran Gokal

Reputation: 11

Magic Square Other Diagonal

My other diagonal method won't work correctly.

public int sumOtherDiag()
{
   int otherDiag = 0;
   for (int i = 0; i < square.length−1; i++)
   {
      otherDiag += square[i][i];
   }
   return otherDiag;
}

I don't have my output to show here, but is there anything that someone sees wrong right off the bat?

This method is supposed to add the elements and get the sum of the second diagonal (starting from the right - down) of a magic square. For example, if my square was

01 04 03

03 05 04

05 02 04

It would output

03 + 05 + 05 = and get 13

But my actual output is printing a number less than what it is supposed too.

(It's hard to explain without my output. I will upload that later when I get access to my program)

Any help will be greatly appreciated, thank you!

Upvotes: 0

Views: 682

Answers (2)

Kick Buttowski
Kick Buttowski

Reputation: 6739

Let's break down your code to see what you did and what you wanted :

with your one loop that you have your coordinates are [0,0] , [1,1] and you missed out [2,2] based on my knowledge because you chose your last index to be less than square.length−1, and you must know index start from zero to less than square.lenght .

if you run your this code :

int[][] array = {{01, 04, 03},
        {03, 05, 04},
        {05, 02, 04}
        };
        int otherDiag = 0;
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i][i]);
        }

your outcome would be this

1
5
4

and you if you chose array.lenght-1 to be excluded your output is

1
5

As you see you left the last index which is 4, which I am sure this is not what you are looking for.

You want to have summation of diagonal elements not vertical elements

The coordinates that you want are

[0,2] , [1,1], and [2,0]

Used my sample as a blue print to figure out what you want

For example, suppose x = new int[3][4], x[0], x[1], and x[2] are one-dimensional arrays and each contains four elements, as shown in the figure x.length is 3, and x[0].length, x[1].length, and x[2].length are 4

enter image description here

How to traverse and intilize the 2D array you can follow following sample as your blue print:

enter image description here

Upvotes: 1

Shahar
Shahar

Reputation: 1677

public int sumOtherDiag()
{
   int otherDiag = 0;
   int count = square.length;
   for (int i = 0; i < square.length; i++)
   {
      otherDiag += square[i][--count];
   }
   return otherDiag;
}

Upvotes: 1

Related Questions