New course! Every coder should learn Generative AI!
Try a free lesson- 3
Why I m getting 16 here instead of 6?
Why this comes to 16? Var x = 1 For (var i =0; I <6 ; I++) X+=i; Document.write(x)
3 Answers
+ 5
At first value of x is 1
Inside for loop x is added with i for every value of i upto i=5 (i<6)
i.e x=1(initial)+0+1+2+3+4+5=16
so final value of x is 16
+ 3
<x> = 1
for...loop goes round 6 times, from 0 to 5
Iteration 1: <x> += 0 => 1
Iteration 2: <x> += 1 => 2
Iteration 3: <x> += 2 => 4
Iteration 4: <x> += 3 => 7
Iteration 5: <x> += 4 => 11
Iteration 6: <x> += 5 => 16
+ 2
If you want to print 6 then write
x += 1 instead of
x+= i