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];"
2 Respuestas
+ 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.
+ 1
Thanks 👍