+ 2
Having trouble finding the logic
I would like to ask why the output of both syntax resulted in 25 ? public class MyClass1 { public static void main(String[]args){ int[] odd = {1,3,5,7,9}; int sum=0; for(int x=0;x<odd.length;x++){ sum= sum+odd[x]; } System.out.println(sum); } } ---------------------------------------------------- public class MyClass1 { public static void main(String[]args){ int[] odd = {1,3,5,7,9}; int sum=0; for(int x=0;x<odd.length;x++){ sum= sum+odd[2]; } System.out.println(sum); } }
3 Answers
+ 2
The first case you're iterating over all elements of the array => 1+3+5+7+9 = 25. In the second case you are adding the odd[2] =>5 exactly 5 times (5 iterations in the loop) so the result is 5*5 = 25 again.
+ 1
Yes, that's right.
0
thanks! so if i put odd[1] then that'd be 3+3+3+3+3 =15 then?