Array and they sum | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 2

Array and they sum

public class Program { public static void main(String[] args) { int[ ] primes = {2, 3, 5, 7}; int sum = 0; for (int x=0;x<primes.length;++x) { sum+=primes[x]; System.out.println(sum); } } } why output is //2 5 10 17?? it should be // 17 ! what I do a wrong? heeelp!)

30th Jan 2018, 6:38 AM
Grey King
Grey  King - avatar
5 Antworten
+ 18
//Array and they sum /*print statement must be out of for loop , if its inside the loop then sum will be printed in each cycle of the loop*/ public class Program { public static void main(String[] args) { int[ ] primes = {2, 3, 5, 7}; int sum = 0; for (int x=0;x<primes.length;++x) { sum+=primes[x]; }System.out.println(sum); } }
30th Jan 2018, 6:59 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 8
That's why! public class Program { public static void main(String[] args) { int[ ] primes = {2, 3, 5, 7}; int sum = 0; for (int x=0;x<primes.length;++x) { sum+=primes[x]; System.out.println(sum); // print to console executes in each loop cycle [2 5 10 17] } } } public class Program { public static void main(String[] args) { int[ ] primes = {2, 3, 5, 7}; int sum = 0; for (int x=0;x<primes.length;++x) { sum+=primes[x]; } System.out.println(sum); // print to console executes once after loop finished its work [17] } }
30th Jan 2018, 7:00 AM
Babak
Babak - avatar
+ 8
@Sensation Try to send your Q in a separate post.
30th Jan 2018, 7:04 AM
Babak
Babak - avatar
+ 2
Gaurav and Babak Thank you guys! Your explanation is help me!
30th Jan 2018, 7:04 AM
Grey King
Grey  King - avatar
+ 1
ok
30th Jan 2018, 7:05 AM
Grey King
Grey  King - avatar