+ 1

2 loops + array

Could sb explain to me why the following code's output is 240 and 480, instead of 2x 240? public class Program { public static void main(String[] args) { int[ ] arr = {14, 25, 67, 89, 45}; int sum = 0; for(int x = 0; x < arr.length; x++) { sum += arr[x]; } System.out.println(sum); // or for(int x: arr) { sum += x; } System.out.println(sum); } }

24th Apr 2018, 5:54 PM
Samsi-Addu
Samsi-Addu - avatar
3 odpowiedzi
+ 4
Because after the first part of the code sum = 240... Then the second part adds 240 again and you end up with 480... If you want 240 twice make sure to do sum = 0 before the second loop
24th Apr 2018, 6:02 PM
cyk
cyk - avatar
+ 3
You declared int sum = 0; outside the block of both for loops. Then, calculated the sum using two for loops, one conventional and the other enhanced. Right? After the execution of first for loop, you got your sum variable as 240, and then, running the second for loop, you added 240 once again in the same sum variable! That's what you got as output ;)
24th Apr 2018, 6:03 PM
777
777 - avatar
+ 1
Ok, thank's :)
24th Apr 2018, 6:05 PM
Samsi-Addu
Samsi-Addu - avatar