+ 1

Can someone pls explain why this code is outputting 4, 6, 11, 5 ?

var arr = [4, 3, 2, 5]; for(var i = 1; i < 3; i++) { arr[i] = arr[i-1] + arr[i + 1]; } alert(arr);

28th May 2021, 3:13 PM
Lara
Lara - avatar
2 Answers
+ 3
arr[i] = arr[i-1] + arr[i + 1]; i=1 arr[1] = arr[0] + arr[2] = 4 + 2 = 6 ; I=2 arr[2] = arr[1] + are[3] = 6+5=11; I=3<3 false, loop exits arr = [ 4, 6,11,5 ] ; Only 2 values changing.. hope it helps.....
28th May 2021, 3:23 PM
Jayakrishna 🇼🇳
+ 3
Yes it helped, i think i understand it now :)
28th May 2021, 3:52 PM
Lara
Lara - avatar