0

help understanding the answer [x=58]

public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); }

30th Jan 2017, 6:17 PM
Nathaniel Ruffer
Nathaniel Ruffer - avatar
4 Réponses
+ 1
sum=sum+myArr[x]; sum=0+6; sum=6+42; sum=48+3; sum=48+7; output 58
30th Jan 2017, 6:31 PM
Somnath Ghosh
Somnath Ghosh - avatar
0
yes the output is 58 but I don't understand why?
30th Jan 2017, 6:31 PM
Nathaniel Ruffer
Nathaniel Ruffer - avatar
0
We are just looping through the array and adding the values of every index to the variable sum
30th Jan 2017, 7:01 PM
Nikolai Russev
Nikolai Russev - avatar
0
the for loop. it is running thru the array of numbers. each time it sees a new number in the array it is adding it to the total. Learn FOR LOOP.. Super useful and once you wrap your head around them very simple
30th Jan 2017, 8:48 PM
LordHill
LordHill - avatar