+ 2

can any body explain me sum += myArr[x]; this part work.

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

25th Jul 2018, 7:51 AM
Yimer Indris
Yimer Indris - avatar
5 Answers
+ 4
QailBee šŸ¤“šŸ¼ Well what coincidence for it no longer surprises me or the tiny fragment of whatever is left of me.
25th Jul 2018, 8:07 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
sum is originally 0. You create a loop which loops from x = 0 to x = myArr.length. Within this loop, myArr[x] would be each array element within myArr. For each execution of the loop, the value of the array element is added to sum. 6 + 42 + 3 + 7 58
25th Jul 2018, 8:02 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
myArr is an array. You can access the single elements of the array with the square brackets. The for loop will start with x = 0. In the for loop, the sum will be += myArr[x] which is same as: sum = sum + myArr[x] which means something is being added. Each iteration x will be increased once till it is te length of the array (4). So with this you sum up each elemenet of the array ( from 0 to 3, with 0 being the first).
25th Jul 2018, 8:03 AM
QailBee šŸ¤“šŸ¼
QailBee šŸ¤“šŸ¼ - avatar
+ 2
It surprises me people do not search their question beforehand Hatsy Rei haha
25th Jul 2018, 8:06 AM
QailBee šŸ¤“šŸ¼
QailBee šŸ¤“šŸ¼ - avatar