0
can we sum up a multi dimensional array??
4 Réponses
+ 3
Yes, use nested loops for that.
int sum = 0;
for(int i = 0; i < myarr.length; i++) {
for(int j = 0; j < myarr[i].length; j++) {
sum += myarr[i][j];
}
}
Edited: Corrected to accept 2d arrays of any size.
+ 2
public class Program
{
public static void main(String[] args) {
int[][] arr = {{2,4},{3,8,6,7}};
int sum = 0;
for(int x = 0; x < arr.length; x++) {
for(int y = 0; y < arr[x].length; y++) {
sum += arr[x][y];
}
}
System.out.println(sum);
}
}
0
thanks Zen it works
0
but this doesn't work
int[] arr ={{2,4},{3,8,6,7}};
int sum =0;
for(int x=0;x<2;x++) {
for(int y=0;y<6;y++) {
sum+=arr[x][y];
}
System.out.println(sum);
IndexOutOfBound exception, how so?