+ 2

39.2 Practice Array Properties & Methods

Hey guys, I've got a couple questions about this problem! 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. My questions: --I saw in another discussion that people are using for loops to solve this? Why would a for loop work for this problem? --Also the code has one variables (elem) which I have no idea what that is? --Lastly, why would I need to use the length property for this? Am I not just adding the number of passed levels to number of points earned? If anyone is able to help, I would be really grateful! Here's the code from the problem: 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 //output console.log(sum);

31st Jan 2022, 9:58 PM
Nate Raia
2 ответов
+ 2
Even that I didn't get to this code coach, you have some misunderstandings: - levels is read from SL server and is the first input; - points is an empty array; - count is a local variable init to 0; - while there is enough count for the input levels, then - elem is read from SL server as the succesive inputs and stored in the points array; - you init with 0 a sum as a local variable and here you need to make a loop where it says //calculate the sum of points. There is no other way to parse the elements of an array. Or you can use some methods like in Ruby, but I don't know enough JS to point that to you. Good luck!
31st Jan 2022, 10:12 PM
Romeo Cojocaru
Romeo Cojocaru - avatar
0
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 (count = 0; count<levels; count++){ sum=sum+points[count]; } //output console.log(sum); }
9th Aug 2022, 8:30 AM
Wenjing Jiang
Wenjing Jiang - avatar