I am supposed to make a program to add all the elements inside the 2D rectangular array but the answer for this is supposed to be 31, instead it prints 33. What am I doing wrong?
Heres the code:
public static int sum(int[][] array) {
int[][] numArray = {
{3, -1, 4, 0},
{5, 9, -2, 6},
{5, 3, 7, -8}
};
int sumOfRow = 0;
for (int i = 0; i < numArray.length; i++) {
sumOfRow += numArray[0][i];
sumOfRow += numArray[1][i];
sumOfRow += numArray[2][i];
}
System.out.println(sumOfRow);
return sumOfRow;
}
numArray.length is the number of rows, and your code treats it as the number of columns, so you ignore the last column of each row. The number of columns in a given row is numArray[i].length.
You should use nested loops:
for (int i = 0; i < numArray.length; i++) {
for (int j = 0; j < numArray[i].length; j++) {
sumOfRow += numArray[i][j];
}
}
As mentioned by the others already, numArray.length refers to the number of rows (or in other words the number of other arrays referenced by the references in numArray), and your code treats it as the number of columns and because there are fewer rows than columns you're getting un-expected results.
Nevertheless, the first index for any two-dimensional array should be the row index and the second should indicate the column index. Eran's answer indicates how to solve your current issue.
However, I just wanted to provide another more ideal solution in Java-8+ to sum the elements of your two-dimensional array.
int sum = Arrays.stream(numArray)
.flatMapToInt(Arrays::stream)
.sum();
It's more ideal because the flatMapToInt is the perfect method for this type of job and simply calling the sum terminal operation should render the results you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With