Having trouble finding the logic | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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); } }

8th Aug 2018, 7:11 PM
Darren Hughs
Darren Hughs - avatar
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.
8th Aug 2018, 7:21 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 1
Yes, that's right.
8th Aug 2018, 7:56 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
0
thanks! so if i put odd[1] then that'd be 3+3+3+3+3 =15 then?
8th Aug 2018, 7:51 PM
Darren Hughs
Darren Hughs - avatar