+ 1
The answer is 17...they said...Can anyone give me more explanations about it...I'm confused I'm not getting
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);
3 Respostas
+ 3
i=0 and 0<5 //true
Since i not equal to 3, else is executed.
So result = 0+0=0;
i=1 and 1<5 //true
Again i not equal to 3, else is executed.
So result = 0+1=1;
Similarly 2<5 // true
So result = 1+2=3;
Now when i becomes 3
i == 3// true
So if is executed and result is incremented by 10.
result = 3+10=13.
Now i=4, i<5 // true
So else is executed and
result = 13+4=17
Next iteration i becomes 5 and i<5 is false so the loop breaks and final result is 17.
+ 3
i = 0
result += 0 //Now result = 0
i = 1
result += 1 //Now result = 1
i = 2
result += 2 //Now result = 3
i = 3
result += 10 //Now result = 13
i = 4
result += 4 //Now result = 17
i = 5 the loop end
+ 1
The answer is 17
I need some explanations about how to get this result