+ 3

Can someone explain to me why 8 is the correct answer in this code below

public class Program { public static void main(String[] args) { int x=2; for(int i=1; i<=3; i++) { x+=i; } System.out.print(x); } } //Output: 8

14th Feb 2019, 4:58 AM
RoadToTheDream
RoadToTheDream - avatar
1 Antwort
+ 5
So first x has the value of 2 and then the loop begins. x += i evaluates to x = 2 + 1 which is 3. For the second run of the loop x += i now evaluates to x = 3 + 2 which is 5. For the third run of the loop x += i evaluates to x = 5 + 3 which is 8. Then once i is 4, i <= 3 is then false so the loop is exited and the value is x (8) is printed.
14th Feb 2019, 5:09 AM
LynTon
LynTon - avatar