0

What’s wrong with the JavaScript coding?

What’s wrong with the JavaScript coding, I think I am very close to the answer. I have got NaN in the output. It’s a practice question in SoloLearn. See 2 lines of coding I wrote below: Question: 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 points. Sample Input 3 1 4 8 Sample Output 13 Explanation The first input represents the number of passed levels, -- in this case, 3 (the size of an array to be created). The next 3 inputs are the points awarded to the player for passing each level. The player gained 1+4+8 points for 3 passed levels, which is then output. Coding: 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; //My coding line1 calculate the sum of points var i = points.length; for (i=1;i<=levels;i++) {sum=points[i]+sum}; //My coding line2 output console.log(sum); }

5th Nov 2020, 9:45 PM
C Yam
C Yam - avatar
4 Answers
+ 5
It should be i<levels
5th Nov 2020, 9:51 PM
Abhay
Abhay - avatar
+ 1
thanks
5th Nov 2020, 10:10 PM
C Yam
C Yam - avatar
0
Also you stored from points[0] but counting from points[1] and points[4] not defined. Must be i=0 & i<levels only..
5th Nov 2020, 10:14 PM
Jayakrishna 🇼🇳
0
i corrected the coding and the following works: var i = points.length; for (i=1;i<=levels;i++) {sum=points[i-1]+sum};
5th Nov 2020, 11:01 PM
C Yam
C Yam - avatar