Assume arr2 is declared as a two-dimensional array of integers. Which of the following segments of code successfully calculates the sum of all elements arr2?
A.int sum = 0;for(int j = 0; j < arr2.length; j++){ for(int k = 0; k < arr2[j].length; k++) { sum += arr2[k][j]; }}
B.
int sum = 0;for(int j = arr2.length − 1; j >= 0; j−−){ for(int k = 0; k < arr2[j].length; k++) { sum += arr2[j][k]; }}
C.
int sum = 0;for(int[] m : arr2){ for(int n : m) { sum += n; }}

Respuesta :

Debel

Answer:

int sum = 0;for(int[] m : arr2){ for(int n : m) { sum += n; }}

Explanation:

Option A is wrong because it will throw an ArrayIndexOutOfBoundsException during the last iteration of the first and second loop.

the number of accessible element in the first dimension of arr2 is from 0 to arr2.length-1 but the loop specify 0 to arr2.length which will be the first cause of the error

while that of the second dimension specify 0 to arr2[j].length  instead of 0 to arr2[j].length-1

Option B is also wrong because the expression j-- will decrement the value of j instead of incrementing it and the second dimension specify 0 to arr2[j].length  instead of 0 to arr2[j].length-1 which will also cause an ArrayIndexOutOfBoundsException.

Option C will successfully calculates the sum of all elements arr2.

ACCESS MORE