Comparing in 2d Arrays

Here's part of my code:
 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970`` ``````bool isMagic (int magic [][4], const int row, const int col) { int originalSum = 0, currentSum; bool result = true; // Add first row for (int row = 0; row < 4; row ++) { originalSum += magic[4][4]; } // Add rows and compare to originalSum for (int row = 1; row < 4; row ++) { currentSum = 0; for ( int col = 0; col < 4; col ++) { currentSum += magic[row][col]; } cout << currentSum << endl; if ( currentSum != originalSum) return (false); } //Add columns and compare to originalSum for ( int col = 0; col < 4; col ++) { currentSum = 0; for (int row = 0; row < 4; row ++) { currentSum += magic [row][col]; } if ( currentSum != originalSum) { return (false); } } // compare diagonal front currentSum = 0; for (int row = 0; row < 4; row ++) { currentSum += magic[row][row]; if ( currentSum != originalSum) { return (false); } } // diagonal back currentSum = 0; for (int row = 0; row < 4; row ++) { currentSum += magic [row] [row - 1]; if ( currentSum != originalSum) { return (false); } else return (true); } }``````

My program is not adding and comparing the results right. The point is to see if the sum of each row, column, and middle diagonal are the same. I'm not sure if there is a mistake in my program or if I'm missing something apparant, but the numbers and comparisons aren't summing correctly. I was going to do comparisons using a while loop, but I am not totally sure how to implement that with the bool statement. Any help is appreciated. (:
Line 9 could be off. U say 'add first row' but u are only adding the same element 4 times.
Line 60. The first time this goes through u are accessing the element magic[0][-1] which will surely cause an out of range exception...
Last edited on
how would I go about making it add just the first row as a comparison tool?
line 30: originalSum += magic[row][4];
 ``12345678`` ``````int i; int sumr0 = 0, sumc0 = 0, sumd = 0; for (i = 0; i < 4; i++) { sumr0 += magic[0][i]; // sum of elements in row 0 sumc0 += magic[i][0]; // sum of elements in col 0 sumd += magic[i][i]; // trace of the array }``````
Topic archived. No new replies allowed.