+ 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
7 Réponses
+ 4
Step 1: i = 1 arr[1] = arr[0] + arr[2] // arr[1] = 4 + 2 = 6 Step 2: i = 2 arr[2] = arr[1] + arr[3] // arr[2] = 6 + 5 = 11 alert(arr); // 4, 6, 11, 5
28th May 2021, 3:23 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 3
Thank you yaroslav and Vasiliy :)
28th May 2021, 4:00 PM
Lara
Lara - avatar
+ 2
1). arr[1] = arr[0] + arr[2] = 4 + 2 = 6; 2). arr[2] = arr[1] + arr[3] = 6 + 5 = 11; arr = [4, 6, 11, 5]; alert(arr);
28th May 2021, 3:27 PM
Solo
Solo - avatar
+ 2
Better say: "Большое Вам спасибо, Ярослав и Василий!" 😉
28th May 2021, 4:09 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
Visualize your code execution (Python, Java, C, C++, JavaScript, Ruby) https://pythontutor.com
28th May 2021, 3:58 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 1
Haha alright. Thank you very much, Yaroslav and Vasily! :)
28th May 2021, 4:30 PM
Lara
Lara - avatar