+ 1

The output is 17 but I don't get why?

What is the output of this code? int result = 0; for (int i = 0; i < 5; i++) { if (i == 3) { result += 10; } else { result += i; } } System.out.println(result);

2nd Mar 2018, 9:02 PM
Sebastian Sivertsen
Sebastian Sivertsen - avatar
4 Antworten
+ 21
loop runs from i=0 to i=4 👉for every no. other than 3 ... sum+=i [for 0,1,2,4] 👉for i=3 , sum+=10 therefore , sum will be 0+1+2+10+4 = 17
3rd Mar 2018, 1:22 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 10
Here you go: ::: OUTPUT :::: Loop(0): 0 + 0 = 0 Loop(1): 0 + 1 = 1 Loop(2): 1 + 2 = 3 Loop(3): 3 + 10 = 13 Loop(4): 13 + 4 = 17 Final Result: 17 https://code.sololearn.com/cuhFGBQPtFoj/#java public class Program { public static void main(String[] args) { int result = 0; for (int i = 0; i < 5; i++) { System.out.print("Loop("+i+"): "); if (i == 3) { System.out.print(result + " + 10 = "); result += 10; System.out.println(result); } else { System.out.print(result + " + " + i + " = "); result += i; System.out.println(result); } } System.out.println("Final Result: " + result); } }
2nd Mar 2018, 9:12 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 4
I always use a debugger if I have difficulties with understanding some code. You go line by line in the loop and watch how variables change. It really helps. You need an ide for this: sharpdevelop is really light or ms visual studio. Sololearn May add debugging capabilities later( I hope) Happy coding
6th Mar 2018, 8:20 PM
wave rider
+ 1
int result = 0; when i=0 ;result=0 for (int i = 0; i < 5; i++) { when i=1; result=0+1 if (i == 3) { when i=2;result= 1+2=3 result += 10; when i=3; result = 3+10=13 } else { when i=4; result = 113+4=17 result += i; when i=5; the loop terminates and } prints result which is 17 } System.out.println(result)
3rd Mar 2018, 3:04 PM
Rupesh Mishra
Rupesh Mishra - avatar