Array Properties & Methods Changllenge | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Array Properties & Methods Changllenge

The chanllenge is: The player receives points after passing each level of a game. The program given takes the number of passed levels as input, followed by the points gained for each level, and creates the corresponding array of points. Complete the program to calculate and output to the console the sum of all gained point. Can someone help me with why the first solution is working but the second one is not working? I suppose they are similar. Solution 1: 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 for (i=0; i<points.length; i++) { sum+=points[i]; } //output console.log(sum); } Solution 2: 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 var n = points[0]; while (n>0) { sum+=points[n]; n--; } //output console.log(sum); }

26th Oct 2022, 10:21 AM
Jingyang Ai
Jingyang Ai - avatar
2 Answers
+ 2
Take sample input : 3 4 5 7 Then according to second code n = points[0] = 4 sum += points[4] ; points[4] is undefined. You may trying reversly summing array elements. Then you need n = levels-1; And then condition must be n >= 0.
26th Oct 2022, 10:30 AM
Jayakrishna 🇮🇳
+ 1
Thank you, Jayakrishna🇮🇳, I got that the level is not in the array. The array is starting with 4 in your answer, I suppose it starts with 3, really appreciate your answer.
26th Oct 2022, 10:38 AM
Jingyang Ai
Jingyang Ai - avatar