No need to scan the full matrix :
long result = 0;
for (int i = 0; i < len; i++)
{
result += matrix[i][i];
if (i < len - 1)
result += matrix[i][i+1];
}
without checking the index at each iteration:
// assign corner value from bottom row to result
long result = matrix[len-1][len-1];
// for each row (except last!) add diagonal and next to diagonal values
for (int i = 0; i < len-1; i++)
result += matrix[i][i] + matrix[i][i+1];
source
share