You could do it for example:
int negNumber = 0;
int sum = 0;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (A[i][j] < 0) {
++negNumber; // increase negatives numbers found
sum += A[i][j]; // add to our result the number
}
}
}
sum = negNumber > 0 ? sum / negNumber : sum; // we need to check if we found at least one negative number
I hope it will help you but be careful! It will return a truncated value (an int).
the ternary operation could be difficult to undertand so you can do it:
if (negNumber > 0) {
sum /= negNumber;
}
2
solved C++ average of negative elements in array [closed]