0

Why this code has output 53 instead of 58??

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

18th Jul 2019, 2:24 PM
Iqra
3 odpowiedzi
+ 9
Since the initial value of x is 1, it'll start adding from 42, not 6. Remember, array index starts from 0. sum = 1+42+3+7 = 53
18th Jul 2019, 2:35 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 4
This works fine public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum=1; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } } Just changed the x value to 0 in for loop Remember that array starts with an index 0 And the output will be 59 not 58 coz you specified sum = 1 so 58 + 1 = 59 Change sum = 0 then the output will be 58
18th Jul 2019, 2:33 PM
deeyae
deeyae - avatar
+ 1
Ohh i got it...thnkxx
18th Jul 2019, 6:42 PM
Iqra