can we sum up a multi dimensional array?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

can we sum up a multi dimensional array??

25th Oct 2016, 11:17 PM
Sandile Mtshali
Sandile Mtshali - avatar
4 Answers
+ 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.
25th Oct 2016, 11:34 PM
Zen
Zen - avatar
+ 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); } }
26th Oct 2016, 11:33 AM
Zen
Zen - avatar
0
thanks Zen it works
26th Oct 2016, 12:51 AM
Sandile Mtshali
Sandile Mtshali - avatar
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?
26th Oct 2016, 1:14 AM
Sandile Mtshali
Sandile Mtshali - avatar