There is a question on 2D array which says
Given a 6*6 matrix we have to print the largest (maximum) hourglass sum found in the matrix. An hourglass is described as:
The error is probably in your sum
function. The way you did it is a bit of an overkill, it'd be much simpler (and readable!) for you to do sth like this:
#define GRID_SIZE (6)
int sum(int a[GRID_SIZE][GRID_SIZE], int i, int j)
{ // Define an hourglass by the index i,j of its central element
int sum = a[j-1][i-1] + a[j-1][i] + a[j-1][i+1] +
a[j][i] +
a[j+1][i-1] + a[j+1][i] + a[j+1][i+1];
return sum;
}
Then just be sure you iterate with sane values (in [1, len-2]):
for (int i = 1; i < (GRID_SIZE-1); i++)
{
for (int j = 1; j < (GRID_SIZE-1); j++)
{
n = sum(arr, i, j);
if (n > max)
max = n;
}
}
Edit: Check that it works here: http://www.cpp.sh/46jhy
Thanks, that was light fun :-).
PS: Make sure you check some coding standards document, it'll make your life a lot easier in the long run, just search for "C code format standard" and get used to trying to work with one you like. Unless you do something new and on your own, you will probably have to follow a standard and maybe not even have a say in which one, so get familiar with general rules and used to following one, whichever you like.