Can anyone explain the following? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Can anyone explain the following?

var arr=[1,2,3,4]; var ct=4 for(let i=0;i<ct;i++){ ct--; arr[i]+=i } document.write(arr); Ans: 1,3,3,4

29th Apr 2019, 9:54 AM
Tahir Usman
Tahir Usman - avatar
4 Answers
+ 6
//You got an array var arr=[1,2,3,4]; //A counter variable named ct var ct=4 //You run a for loop from 0 as long as i is less than ct for(let i=0;i<ct;i++){ //we decrement ct each time the loop runs ct--; //we increment the array element at position i by the value of i whenever this loop runs arr[i]+=i // 1st run of this loop //arr[0]+=0 //Now i is 1, ct is 3(ct--), original array is unchanged //2nd run of this loop //arr[1]+=1 //Now i is 2, ct is 2(ct--) and now we also incremented arr[1] by 1 [1, 2, 3, 5] -> [1, 3, 4, 5] //loop terminates as i is no longer less than ct //i = 3, ct=3 } document.write(arr) //print
29th Apr 2019, 11:02 AM
Lord Krishna
Lord Krishna - avatar
+ 5
For the first value it adds 0 So 1 still is 1 In the second run of the loop ct becomes 2 And i is 1 So to the 2 in the arr it adds 1. Then i becomes 2 and is no longer smaller than ct and so the loop stops and prints 1 3 3 4
29th Apr 2019, 9:58 AM
Dragonxiv
Dragonxiv - avatar
+ 4
29th Apr 2019, 12:15 PM
Tahir Usman
Tahir Usman - avatar
+ 3
Dragonxiv Thanks but I didn't get, may you please explain it in a gradual manner.
29th Apr 2019, 10:37 AM
Tahir Usman
Tahir Usman - avatar