+ 1

can someone explain the x.length-1 in this program and why sum ends up to be 7? var x=[1,4,2,1]; var sum=0; for (i=0;i<x.length-1;i++){ sum+=x[i]; } document.write(sum)

16th Sep 2016, 1:23 PM
Mercurius
Mercurius - avatar
2 Answers
+ 3
Array indexes start at 0. length gives you the length of the array, here 4. For i to go through all the index values of the array, it would need to go from 0 to 3, but here it only goes from 0 to 2, hence why only the first 3 array values are added. Parenthesis: for (i=0;i<x.length;i++) is quite common to browse an array x. for (i=1;i<=n;i++) to browse all the values from 1 to n is common too.
16th Sep 2016, 1:36 PM
Zen
Zen - avatar
+ 1
Zen has explained the reasoning brilliantly. So for simplicity you're error is because of the "-1" you inserted hence why it doesn't get to the last digit of the array. So just write "i < x.length".
16th Sep 2016, 10:27 PM
Ousmane Diaw