Assume you are given a boolean variable named isNegative and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that assign true to isNegative if more integer elements in entire 2-dimensional array are negative than not.

Assume you are given a boolean variable named isNegative and a 2-dimensional array of ints that has been created and assigned  to a2d. Write some statements that assign true to isNegative if more integer elements in entire 2-dimensional array are negative than not.

LANGUAGE: JAVA

CHALLENGE:

Assume you are given a boolean variable named isNegative and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that assign true to isNegative if more integer elements in entire 2-dimensional array are negative than not.

SOLUTION:

int negatives = 0;
int positives = 0;
for (int i=0; i<a2d.length; i++)
for (int j=0; j<a2d[i].length; j++){
   if (a2d[i][j] > 0) positives++;
   if (a2d[i][j] < 0) negatives++;
}
if (negatives > positives)
isNegative = true;
else

isNegative = false;

Add comment