Every cell has between 3 and 8 neighbors. For each potential neighbor, you first need to determine if it is a valid neighbor. If it isn't, you don't add to your count. If it is valid, then you add the cells value to your count of neighbors.
Look at the matrix of neighbors:
0 1 2
3 X 4
5 6 7
For neighbor 0 to be valid, then row can't be 0, and column can't be 0, right? No cell in the first row or the first column has a valid neighbor one row up and one column to the left.
For neighbor 1 to be valid, then row can't be 0, right? No cell in the first row has a neighbor in the row above it.
For neighbor 7 to be valid, then row can't be the last row, or the last column. The last row doesn't have a row after it. The last column doesn't have a column after it, so there is no neighbor at row + 1, col + 1, is there?
And so on. You can derive a simple rule for each neighbor that way.
In pseudo code, you could do something like this, assuming you are trying to count the neighbors of cell r,c, and have variables maxRow = Rows-1 (max valid INDEX) and maxCol = Cols-1 (max valid INDEX). For a 5X5,m maxRow and maxCol would be 4.
count = 0
// neighbor 0:
count += ( r > 0 && c > 0 ) ? cell[r-1][c-1] : 0;
// neighbor 1:
count += (r > 0) ? cell[r-1][c] : 0;
// neighbor 2:
count += (r > 0 && c < maxCol) ? cell[r-1][c+1] : 0;
... And so on down to:
// neighbor 7
count += (r < maxRow && c < maxCol) ? cell[r+1][c+1] : 0;
So basically you would try to add to count 8 times, once for each neighbor. The ? : ternary operator lets you first test the condition: Is r and c valid for this neighbor. If it is, add the value of that neighgbor. If it isn't add 0 (which, obviously, is just a NOP).
You could do the same thing using if/else statements, but I always find 8 different branches through if/else logic hard to read and hard to debug. The approach above has the advantage that each line of code is independent. It's either right, or it's wrong. You can prove to yourself that it's right or wrong by looking at just 1 line of code. No need to follow if/else logic to 3 levels.
Do note: It fails for a 2x2 matrix. They are a special case. (as is 1x1).
Hope that makes sense. (And that I'm not off by 1 in there somewhere ;-)