0

Arrays properties and methods practice

Can any one please tell me why this one doesn't work: function main() { //take the number of passed levels var levels = parseInt(readLine(),10); var points = new Array(); var count = 0; while(count<levels){ var elem = parseInt(readLine(),10); points[count] = elem; count++; } var sum = 0; //calculate the sum of points while(count!=0) { sum += points[count]; count-- } //output console.log(sum); } but this one does? function main() { //take the number of passed levels var levels = parseInt(readLine(),10); var points = new Array(); var count = 0; while(count<levels){ var elem = parseInt(readLine(),10); points[count] = elem; count++; } var sum = 0; //calculate the sum of points a = 0; while(a<points.length) { sum += points[a]; a++ } //output console.log(sum); }

14th Jan 2024, 8:28 PM
Marc Andrew Picardal
Marc Andrew Picardal - avatar
2 Respuestas
+ 4
Marc Andrew Picardal , Please add a tag for the language.
14th Jan 2024, 8:50 PM
Rain
Rain - avatar
+ 3
Marc Andrew Picardal the first code mistakenly uses count as the array index whereas it should be count-1. I would recommend moving up count--, so it happens before using count as the index. count--; sum += points[count]; or try this sum += points[--count];
14th Jan 2024, 9:20 PM
Brian
Brian - avatar