Can somebody explain why the output of this code 17? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 11

Can somebody explain why the output of this code 17?

int result = 0; for (int i = 0; i < 5; i++) { if (i == 3) { result += 10; } else { result += i; } } System.out.println(result);

12th Mar 2017, 9:57 PM
Wilson Bol
Wilson Bol - avatar
3 Antworten
+ 21
Normally it loops through and adds i to result, except when i is 3, in which case it adds 10. Here it is: Loop # i val. result val. 1. 0. 0 2. 1. 1 (0+1) 3. 2. 3 (1+2) 4. 3. 13 (3+10 because i is 3) 5. 4. 17 (13+4) 6. 5. i is not < 5 so the loop body is not executed. It exits the loop and prints result, which is 17. I hope this helps.
12th Mar 2017, 10:06 PM
J.G.
J.G. - avatar
+ 20
thank you.
13th Mar 2017, 1:42 AM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 10
Thanks
13th Mar 2017, 3:25 PM
Wilson Bol
Wilson Bol - avatar