+ 2

Can anyone please tell me how it's output is correct!! This is a js project this will count points of every level but how !

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; var i = 0; while(i < levels){ sum += points[i] i++; } console.log(sum); }

10th Feb 2022, 6:02 PM
Coderado
Coderado - avatar
4 Antworten
+ 1
If input is : Ex: 3 // (levels) 20 // points[0] 30 //points[1] 40 //points[2] var sum = 0; var i = 0; while(i < levels){ //0<3 is true sum += points[i] //sum+=20=>0+20=>sum=20 i++; //I=1 In next iteration: 1<3 is true, sum+=points[1] => sum= 20+30=>sum=50 I++;//I=2 In next iteration: 2<3 is true, sum+=points[2] => sum= 50+40=>sum=90 I++ //I=3 3<3 is false so here loop stops.. } console.log(sum); //this will output : 90
11th Feb 2022, 9:33 AM
Jayakrishna 🇮🇳
+ 2
Thankyou bro 😊
11th Feb 2022, 12:09 PM
Coderado
Coderado - avatar
+ 1
My difficulty is after variable i can you explain me how this code will sum all the scores
11th Feb 2022, 8:17 AM
Coderado
Coderado - avatar
0
levels input is how many scores do you need to read as input! Your first while loop is reading scores into points array. Your second while loop calculates sum of array elements which are scores at each level.. Ex: 3 // levels 20 30 40 20+30+40=90 is the sum where is your difficulty in understanding code ? tell that specific part, if still not clear.
10th Feb 2022, 6:22 PM
Jayakrishna 🇮🇳