0

Java Array Summing

int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); // 58 1. Can Someone explain me the mechanism of this code? 2. what is "myArr[x];"

14th Mar 2020, 5:45 AM
faakeer
faakeer - avatar
2 Answers
+ 1
myArr is the array that contains the elements {6,42,3,7}. In order to sum these elements, we need to iterate the array. The iterations happens with this for loop where x is used to access the specific position of the array. In Java arrays, the index starts from 0, so that why we have x=0, and reaches the length of the array minus 1. In our case, x will have value from 0 to 3 (4 elements) and myArr[x] will access the position of the array with index x and add the elements of this position in the sum.
14th Mar 2020, 5:54 AM
Evangelia Spachou
Evangelia Spachou - avatar
+ 1
Thanks 👍
14th Mar 2020, 6:05 AM
faakeer
faakeer - avatar