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); } }
3 Respuestas
+ 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
+ 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
+ 1
Ohh i got it...thnkxx