105k views
0 votes
assume that an int variable named sum has been declared, and a two-dimensional array of ints named a2d has been created and assigned values. write some statements that calculate the sum of all the elements in the two-dimensional array and assign the value to sum.

1 Answer

4 votes

Final answer:

Here is the code:

sum = 0; // Initialize sum to zero
for (int i = 0; i < a2d.length; i++) {
for (int j = 0; j < a2d[i].length; j++) {
sum += a2d[i][j]; // Add each element to sum
}
}

Step-by-step explanation:

If you want to calculate the sum of all the elements in a two-dimensional array named a2d and assign it to an int variable named sum, you can use a nested for-loop to iterate through the array.

Here is how you could write the code:

sum = 0; // Initialize sum to zero
for (int i = 0; i < a2d.length; i++) {
for (int j = 0; j < a2d[i].length; j++) {
sum += a2d [i] [j]; // Add each element to sum
}
}
The outer loop runs through each row of the 2D array, while the inner loop runs through each element of the current row, adding each element's value to the sum.
User Cagatay
by
8.5k points