+ 2

# why does this code print 6? Please tell me in deep please.

2 Answers

+ 11

First loop:
x is 0, i is 1
(x + i) is 1, assigned to x
Second loop:
x is 1, i is 2
(x + i) is 3, assigned to x
Third loop:
x is 3, i is 3
(x + i) is 6, assigned to x
Outputs x:
outputs 6

+ 1

You enter the for-loop with x=0, i=1.
x get reassigned: x = 0 + 1,
i++ lets i become i+1 = 2.
As 2<4, you stay in the loop with x=1, i=2.
x get reassigned: x = 1 + 2 = 3.
i++ lets i become i+1 = 2.
As 3<4, you stay in the loop with x=3, i=3.
x get reassigned: x = 3 + 3 = 6.
i++ lets i become i+1 = 4.
Now 4<4 is false and the loop exits with x being 6.
You print x, which has value 6.